Muokkaa

Jaa


.NET Framework 4 migration issues

This article describes migration issues between .NET Framework version 3.5 Service Pack 1 and .NET Framework version 4, including fixes, changes for standards compliance and security, and changes based on customer feedback. Most of these changes do not require any programming modifications in your applications. For those that may involve modifications, see the Recommended changes column of the table. Notable changes are broken down by area, for example, ASP.NET and Windows Presentation Foundation (WPF).

For a higher-level overview of the issues in this article, see Migration Guide to .NET Framework 4.

For information about new features, see What's New in .NET Framework 4.

ASP.NET and Web

Namespaces: System.Web, System.Web.Mobile, System.Web.Security, System.Web.UI.WebControls

Assembly: System.Web (in System.Web.dll)

Feature Differences from 3.5 SP1 Recommended changes
Browser definition files 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.

The HttpBrowserCapabilities object (which is exposed by the page's Request.Browse property) is driven by the browser definition files. Therefore, the information that is returned by accessing a property of this object in ASP.NET 4 might be different than the information that was returned in an earlier version of ASP.NET.
If your application relies on the old browser definition files, you can copy them 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, see the https://www.asp.net/mobile Web site.
Child applications running under mixed versions of ASP.NET 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 specific error that occurs depends on whether the application runs under IIS 6.0, or under IIS 7 or IIS 7.5. You can make changes to the configuration files of the affected applications so that the configuration system correctly recognizes the ASP.NET 4 application. For information about the changes you must make, see the section "ASP.NET 4 Child Applications Fail to Start When Under ASP.NET 2.0 or ASP.NET 3.5 Applications" in the document ASP.NET 4 Breaking Changes on the ASP.NET Web site.
ClientID changes The new 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. The default setting is now Predictable. For more information, see ASP.NET Web Server Control Identification. If you use Visual Studio 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 .NET Framework. However, if you upgrade an application by changing the application pool in IIS to target .NET Framework 4, ASP.NET uses the new mode by default. To disable the new client ID mode, add the following setting to the Web.config file:

<pages clientIDMode="AutoID" />
Code access security (CAS) ASP.NET 2.0 NET features that were added in ASP.NET 3.5 use the .NET Framework 1.1 and .NET Framework 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 might fail with various security exceptions. Partial-trust applications that rely on extensive modifications to machine CAS policy might also fail and throw security exceptions. You can revert partial-trust ASP.NET 4 applications to the behavior of ASP.NET 1.1 and 2.0 by using the new legacyCasModel attribute in the trust configuration element, as shown in the following example:

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

Important: Reverting to the older CAS model might represent reduced security.

For more information about the new ASP.NET 4 code access security model, see Code Access Security in ASP.NET 4 Applications.
Configuration files The root configuration files (the machine.config file and the root Web.config file) for .NET Framework and ASP.NET 4 have been updated to include most of the boilerplate configuration information that was found in the application Web.config files in ASP.NET 3.5. 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 errors or IIS errors. Upgrade ASP.NET 3.5 applications to ASP.NET 4 by using the project upgrade tools in Visual Studio. 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, you can run ASP.NET 3.5 applications using .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 .NET Framework 4 and under IIS 7 or IIS 7.5. The specific change you must make depends on the combination of software you are working with, including Service Pack (SP) releases. For information about the possible software combinations that are affected by this change and how to resolve problems with specific combinations, see the section "Configuration Errors Related to New ASP.NET 4 Root Configuration" in the document ASP.NET 4 Breaking Changes on the ASP.NET Web site.
Control rendering In previous versions of ASP.NET, some controls emitted markup that you could not disable. By default, this type of markup is no longer generated in ASP.NET 4. The rendering changes affect the following controls:

* 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).
If you use Visual Studio 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 .NET Framework 4, ASP.NET uses the new rendering mode by default. To disable the new rendering mode, add the following setting to the Web.config file:

<pages controlRenderingCompatibilityVersion="3.5" />
Event handlers in default documents ASP.NET 4 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. 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, but ASP.NET now renders the HTML opening form tag as in the following example:

<form action="" />

When the action attribute is an empty string, the IIS DefaultDocumentModule object creates 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, such as 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. Therefore there is no information available for the .aspx page handler to determine what event (if any) should be raised. As a result, none of the postback event handlers for the affected .aspx page run.
For information about ways to work around problems that might arise as a result of this change, see "Event Handlers Might Not Be Not Raised in a Default Document in IIS 7 or IIS 7.5 Integrated Mode" in the document ASP.NET 4 Breaking Changes on the ASP.NET Web site.
Hashing algorithm 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 uses the HMACSHA256 algorithm for hash operations on cookies and view state. Earlier versions of ASP.NET used the older HMACSHA1 algorithm. If you run applications that mix ASP.NET 2.0 and ASP.NET 4, where data such as forms authentication cookies must work across .NET Framework versions, configure an ASP.NET 4 Web application to use the older HMACSHA1 algorithm by adding the following setting in the Web.config file:

<machineKey validation="SHA1" />
Hosting controls in Internet Explorer You can no longer host Windows Forms controls in Internet Explorer, because there are better solutions for hosting controls on the Web. Therefore, the IEHost.dll and IEExec.exe assemblies have been removed from .NET Framework. You can use the following technologies for custom control development in Web applications:

* You can create a Silverlight application and configure it to run outside the browser. For more information, see Out-of-Browser Support.
* You can build a XAML browser application (XBAP) to take advantage of WPF capabilities (requires .NET Framework on client machines). For more information, see WPF XAML Browser Applications Overview.
HtmlEncode and UrlEncode methods 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 &#39;
* The UrlEncode method encodes instances of the single quotation mark as %27
Examine your code for places where you use the HtmlEncode and UrlEncode methods, and make sure that the change in encoding does not result in a change that would affect your application.
HttpException errors in ASP.NET 2.0 applications 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. * If ASP.NET 4 is not required in order to run the Web site, remap the site to use ASP.NET 2.0 instead.

-or-

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

-or-

* Disable extensionless URLs. For more information, see "ASP.NET 2.0 Applications Might Generate HttpException Errors That Reference eurl.axd" in the document ASP.NET 4 Breaking Changes on the ASP.NET Web site.
Membership types Some types (for example, MembershipProvider) that are used in ASP.NET membership have been moved from System.Web.dll to the System.Web.ApplicationServices.dll assembly. The types were moved in order to resolve architectural layering dependencies between types in the client and in extended .NET Framework SKUs. Class libraries that have been upgraded from earlier versions of ASP.NET and that use membership types that have been moved might fail to compile when used in an ASP.NET 4 project. If so, add a reference in the class library project to System.Web.ApplicationServices.dll.
Menu control changes Changes to the Menu control result in the following behavior:

* If MenuRenderingMode is set to List, or if MenuRenderingMode is set to Default and ControlRenderingCompatibilityVersion is set to 4.0 or later, the PopOutImageUrl property has no effect.
* If the path that is set in the StaticPopOutImageUrl and DynamicPopOutImageUrl properties contains a backslash (\), the images do not render. (In earlier versions of ASP.NET, the path could include a backslash.)
* Instead of setting the PopOutImageUrl property for individual menu items, set the StaticPopOutImageUrl or DynamicPopOutImageUrl of the parent Menu control.

-or-

Set MenuRenderingMode to Table, or set MenuRenderingMode to Default and set ControlRenderingCompatibilityVersion to 3.5. These settings cause the Menu control to use the HTML table-based layout that it used in earlier versions of ASP.NET.
* If the path in the StaticPopOutImageUrl or DynamicPopOutImageUrl property contains a backslash (\), substitute a slash character (/).
Mobile assembly in Web.config 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 system.web/compilation. To improve performance, the reference to this assembly has been removed.

Note: The System.Web.Mobile.dll assembly and the ASP.NET mobile controls are included in ASP.NET 4, but they are deprecated.
If you want to use types from this assembly, add a reference to the assembly in either the root Web.config file or in an application Web.config file.
Output caching In ASP.NET 1.0, a bug caused cached pages that specified Location="ServerAndClient" as an output€"cache setting to emit a Vary:* HTTP header in the response. This had the effect of telling client browsers to never cache the page locally. In ASP.NET 1.1, the SetOmitVaryStar method was added, which could be called in order to suppress the Vary:* header. However, bug reports suggest that developers are unaware of the existing SetOmitVaryStar behavior.

In ASP.NET 4, the Vary:* HTTP header is no longer emitted from responses that specify the following directive:

<%@ OutputCache Location="ServerAndClient" %>

As a result, the SetOmitVaryStar method is no longer needed in order to suppress the Vary:* header. In applications that specify "ServerAndClient" for the Location attribute, pages will be cacheable in the browser without requiring that you call SetOmitVaryStar.
If pages in the application must emit Vary:*, call the AppendHeader method as shown in the following example:

System.Web.HttpResponse.AppendHeader("Vary","*");

Alternatively, you can change the value of the output caching Location attribute to "Server".
Page parsing The page parser for ASP.NET Web pages (.aspx files) and user controls (.ascx files) is stricter in ASP.NET 4 than in earlier versions of ASP.NET, and it flags more markup as invalid than in earlier versions. Examine error messages that are produced when a page runs and fix errors that result from invalid markup.
Passport types The Passport support built into ASP.NET 2.0 is obsolete and is unsupported due to changes in Passport (now Live ID SDK). As a result, the types related to Passport in System.Web.Security are now marked with the ObsoleteAttribute attribute. Change any code that uses Passport types in the System.Web.Security namespace (for example, PassportIdentity) to use the Windows Live ID SDK.
PathInfo information in the FilePath property ASP.NET 4 no longer includes the PathInfo value in the return values from properties such as FilePath, AppRelativeCurrentExecutionFilePath, and CurrentExecutionFilePath. Instead, the PathInfo information is available in PathInfo. For example, imagine the following URL fragment:

/testapp/Action.mvc/SomeAction

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

* FilePath: /testapp/Action.mvc/SomeAction
* PathInfo: (empty)

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

* FilePath: /testapp/Action.mvc
* PathInfo: SomeAction
Examine your code for places where you rely on properties of the HttpRequest class to return path information; change the code to reflect the changes in how path information is returned.
Request validation To improve request validation, the ASP.NET request validation is invoked earlier in the request life cycle. As a result, request validation runs for requests that are not for .aspx files, such as for Web service calls and for custom handlers. Request validation will also be active when custom HTTP modules are running in the request processing pipeline.

As a result of this change, requests for resources other than .aspx files might throw request validation errors. Custom code that runs in the request pipeline (for example, custom HTTP modules) might also throw request validation errors.
If necessary, you can revert to the old behavior of having only .aspx pages triggering request validation by using the following setting in the Web configuration file:

<httpRuntime requestValidationMode="2.0" />

Warning: If you revert to the old behavior, make sure that all code in existing handlers, modules, and other custom code performs checks for potentially unsafe HTTP inputs that could be XSS attack vectors.
Routing If you create a file system Web site in Visual Studio 2010 and the Web site is in a folder that contains a dot (.) in the folder name, URL routing will not work reliably. An HTTP 404 error is returned from some virtual paths. This occurs because Visual Studio 2010 launches the Visual Studio Development Server using an incorrect path for the root virtual directory. * In the Properties page for the file-based Web site, change the Virtual Path attribute to "/".

-or-

* Create a Web application project instead of a Web site project. Web application projects do not have this issue, and URL routing works even if the project folder has a dot in its name.

-or-

* Create an HTTP-based Web site that is hosted in IIS. IIS-hosted Web sites can have dots in the virtual path as well as in the project file folder.
SharePoint sites If you try to run an ASP.NET 4 Web site that is deployed as a child of a SharePoint Web site that contains a custom partial-trust level named WSS_Minimal, you will see the following error:

Could not find permission set named 'ASP.Net'.
Currently, no versions of SharePoint are compatible with ASP.NET. As a result, you should not attempt to run an ASP.NET 4 Web site as a child of a SharePoint Web site.
XHTML 1.1 standards To enable XHTML 1.1 compliance for new Web sites, the ASP.NET controls in .NET Framework 4 will generate XHTML 1.1 compliant HTML. This rendering is enabled using the following option in the Web.config file inside the <system.Web> element:

<pages controlRenderingCompatibilityVersion="4.0"/>

This option is set by default to 4.0. Web projects that are upgraded from Visual Studio 2008 have the 3.5 setting enabled for compatibility.
None.

Core

General features

Feature Differences from 3.5 SP1 Recommended changes
CardSpace Windows CardSpace is no longer included in .NET Framework; it is provided separately. Download Windows CardSpace from the Microsoft Download Center.
Configuration files Corrections have been made in how .NET Framework accesses application configuration files. If your application configuration file is named application-name.config, rename it to application-name.exe.config. For example, rename MyApp.config to MyApp.exe.config.
C# code compiler The Compiler, CompilerError, and ErrorLevel classes that were in the Microsoft.CSharp namespace are no longer available, and their assembly (cscompmgd.dll) is no longer included in .NET Framework. Use the CodeDomProvider class and other classes in the System.CodeDom.Compiler namespace. For more information, see Using the CodeDOM.
Hosting (unmanaged API) To improve hosting capabilities, some of the hosting activation APIs have been deprecated. In-process side-by-side execution features enable an application to load and start multiple versions of .NET Framework in the same process. For example, you can run applications that load add-ins (or components) that are based on .NET Framework 2.0 SP1 and add-ins that are based on .NET Framework 4 in the same process. Older components continue to use the older .NET Framework version, and new components use the new .NET Framework version. Use the configurations described in In-Process Side-by-Side Execution.
New security model The code access security (CAS) policy has been turned off and replaced with a simplified model, as described in Security Changes in .NET Framework 4. Modifications may be required if you depend on CAS in your applications. For more information, see Code Access Security Policy Compatibility and Migration.

Date and time

Namespace: System

Assembly: mscorlib (in mscorlib.dll)

Feature Differences from 3.5 SP1 Recommended changes
Daylight savings To be consistent with the system clock, time properties (such as Local and Now) now use operating system rules instead of other .NET Framework data for daylight saving time operations. None.
Formatting strings To support culture-sensitive formatting, the TimeSpan structure includes new overloads of the ToString, Parse, and TryParse methods in addition to new ParseExact and TryParseExact methods. None.

Globalization

For a list of new neutral and specific cultures, see What's New in Globalization and Localization.

Namespace: System.Globalization

Assembly: mscorlib (in mscorlib.dll)

Feature Differences from 3.5 SP1 Recommended changes
Culture names The following name changes affect the German, Divehi, and African cultures:

* CurrencyEnglishName: The currency name for the German (Switzerland) (de-CH) culture has changed from "sFr." to "Fr.".
* LongDatePattern: The long date pattern for the Divehi (Maldives) (dv-MV) culture has changed from "dd/MMMM/yyyy" to "dd/MM/yyyy".
* PMDesignator: The P.M. designator of the Afrikaans (South Africa) (af-ZA) culture has changed from "nm" to "PM".
Note culture name changes.
LCID parameter To be consistent with expected behavior in automation server settings, the CLR no longer passes the current culture for the LCID parameter to unmanaged COM-based applications. Instead, it passes 1033 (en-us) for the culture. No modifications necessary except for native applications that require a specified culture.
Obsolete culture types The CultureTypes and CultureTypes culture types are now obsolete.

For backward compatibility, CultureTypes now returns neutral and specific cultures that were included with the previous .NET Framework, and CultureTypes now returns an empty list.
Use other values of the CultureTypes enumeration.
Retrieving culture Beginning with Windows 7, .NET Framework 4 retrieves culture information from the operating system instead of storing the data itself. In addition, .NET Framework synchronizes with Windows for sorting and casing data. None.
Unicode 5.1 standards .NET Framework now supports all Unicode 5.1 characters -- an addition of approximately 1400 characters. The additional characters include new symbols, arrows, diacritics, punctuation, mathematical symbols, CJK strokes and ideographs, additional Malayalam and Telugu numeric characters, and various Myanmar, Latin, Arabic, Greek, Mongolian, and Cyrillic characters. The following new scripts are supported with Unicode 5.1: Sundanese, Lepcha, Ol Chiki, Vai, Saurashtra, Kayah Li, Rejang, Gurmukhi, Odia, Tamil, Telugu, and Malayalam characters and Cham. None.

Exceptions

Namespaces: System, System.Runtime.ExceptionServices

Assembly: mscorlib (in mscorlib.dll)

Feature Differences from 3.5 SP1 Recommended changes
Exceptions for corrupted process state The CLR no longer delivers exceptions for corrupted process state to exception handlers in managed code. These exceptions indicate that the state of a process has been corrupted. We do not recommend that you run your application in this state.

For more information, see the HandleProcessCorruptedStateExceptionsAttribute and the entry Handling Corrupted State Exceptions in the MSDN magazine.
Execution engine exceptions ExecutionEngineException is now obsolete, because a catchable exception will allow an unstable process to continue to run. This change improves predictability and reliability in the runtime. Use an InvalidOperationException to signal the condition.

Reflection

Namespace: System.Reflection

Assembly: mscorlib (in mscorlib.dll)

Feature Differences from 3.5 SP1 Recommended changes
Assembly hash algorithms The HashAlgorithm property now returns AssemblyHashAlgorithm, because the runtime does not know the hash algorithm of the referenced assembly when the assembly is not loaded. (This refers to using the property on a referenced assembly such as that returned by the GetReferencedAssemblies method.) None.
Assembly loading To prevent redundant loading of assemblies and to save virtual address space, the CLR now loads assemblies by using only the Win32 MapViewOfFile function. It no longer also calls the LoadLibrary function.

This change affects diagnostic applications in the following ways:

* A ProcessModuleCollection will no longer contain any modules from a class library (.dll file), as obtained from a call to Process.GetCurrentProcess().Modules.
* Win32 applications that use the EnumProcessModules function will not see all managed modules listed.
None.
Declaring type The DeclaringType property now correctly returns null when the type does not have a declaring type. None.
Delegates A delegate now throws an ArgumentNullException instead of a NullReferenceException when a null value is passed to the delegate's constructor. Ensure that any exception handling catches ArgumentNullException.
Global assembly cache location change For .NET Framework 4 assemblies, the global assembly cache has been moved from the Windows directory (%WINDIR%) to the Microsoft.Net subdirectory (%WINDIR%\Microsoft.Net). Assemblies from earlier versions remain in the older directory.

The unmanaged ASM_CACHE_FLAGS enumeration contains the new ASM_CACHE_ROOT_EX flag. This flag gets the cache location for .NET Framework 4 assemblies, which can be obtained by the GetCachePath function.
None, assuming that applications do not use explicit paths to assemblies, which is not a recommended practice.
Global assembly cache tool The Gacutil.exe (Global Assembly Cache Tool) no longer supports the shell plugin viewer. None.

Interoperability

Namespace: System.Runtime.InteropServices

Assembly: mscorlib (in mscorlib.dll)

Feature Differences from 3.5 SP1 Recommended changes
Buffer length (unmanaged API) To save memory, the functionality for the pBufferLengthOffset parameter for the ICorProfilerInfo2::GetStringLayout method has been changed to match the pStringLengthOffset parameter. Both parameters now point to the offset location of the string's length. Buffer length has been removed from the representation of the string class. Remove any dependency on the buffer length.
JIT debugging To simplify registration for just-in-time (JIT) debugging, the .NET Framework debugger now uses only the AeDebug registry key, which controls the JIT debugging behavior for native code. This change results in the following:

* You can no longer register two different debuggers for managed and native code.
* You can no longer start the debugger automatically for a non-interactive process, but you can prompt the user for an interactive process.
* You are no longer notified when the debugger fails to start, or when there is no registered debugger that should be started.
* Auto-launch policies that depend on the interactivity of the application are no longer supported.
Adjust debugging operations as required.
Platform invoke To improve performance in interoperability with unmanaged code, incorrect calling conventions in a platform invoke now cause the application to fail. In previous versions, the marshalling layer resolved these errors up the stack. Debugging your applications in Microsoft Visual Studio alerts you to these errors so you can correct them.

If you have binaries that cannot be updated, you can include the <NetFx40_PInvokeStackResilience> element in your application's configuration file to enable calling errors to be resolved up the stack as in earlier versions. However, this may affect the performance of your application.
Removed interfaces (unmanaged API) To avoid developer confusion, the following interfaces were removed, because they did not provide any useful run-time scenarios, and the CLR did not provide or accept any implementations:

* INativeImageINativeImageDependency
* INativeImageInstallInfo
* INativeImageEvaluate
* INativeImageConverter
* ICorModule
* IMetaDataConverter
None.

Data

This section describes migration issues for using data sets and SQL clients, the Entity Framework, LINQ to SQL, and WCF Data Servers (formerly known as ADO.NET Data Services).

DataSet and SQL Client

The following table describes improvements to features that previously had limitations or other issues.

Namespaces: System.Data, System.Data.Objects.DataClasses, System.Data.SqlClient

Assemblies: System.Data (in System.Data.dll), System.Data.Entity (in System.Data.Entity.dll)

Feature Differences from 3.5 SP1
POCO Scenarios The IRelatedEnd interface has new methods to improve its usability in Plain Old CLR Object (POCO) scenarios. These new methods take an Object instead of an IEntityWithRelationships entity as a parameter.
Editing Rows The IndexOf method, as implemented by the DataView class, now correctly returns the value of a row that is being edited, instead of returning -1.
Events The PropertyChanged event is now raised when a row is in a modified state and the RejectChanges method is called. This change makes it easier to create UI controls that expose the contents of a DataSet object.
Exceptions The Prepare method now throws an InvalidOperationException when a connection is not set or open instead of a NullReferenceException.
Mapping Views Query view mapping errors are now caught at design time instead of throwing a NullReferenceException at run time.

Mapping validation now catches the error in which two association sets in Conceptual Schema (CSDL) are mapped to the same column.
Transactions If an application tries to execute a statement on a connection after a transaction has been completed (including aborted or rolled back), an InvalidOperationException is now thrown. Previous versions did not throw an exception and let you execute additional commands even if a transaction was aborted.

Entity Framework

The following table describes improvements to features that previously had limitations or other issues.

Namespaces: System.Data, System.Data.Objects, System.Data.Objects.DataClasses

Assemblies: System.Data.Entity (in System.Data.Entity.dll)

Feature Differences from 3.5 SP1
Entity objects There is now parity between the Detach method and the state of the entity object when the SaveChanges method is called. This improved consistency prevents unexpected exceptions from being thrown.
Entity SQL Rules have been improved for identifier resolutions in Entity SQL.

The Entity SQL parser has improved logic for resolving multipart identifiers.
Structural annotations The Entity Framework now recognizes structural annotations.
Queries The following improvements were made in queries:

* A GroupBy query using a null key over an empty collection will not return any rows, regardless if there are any additional selects in the query.
* Generated SQL in LINQ and Entity-SQL queries now treat string parameters as non-Unicode values by default.

LINQ to SQL

The following table describes improvements to features that previously had limitations or other issues.

Namespace: System.Data.Linq

Assembly: System.Data.Linq (in System.Data.Linq.dll)

Feature Differences from 3.5 SP1
Events A EntitySet<TEntity> collection now raises the ListChanged event for add and remove operations if the EntitySet<TEntity> is unloaded, in addition to raising the event when the collection is loaded.
Queries Skip(0) is no longer ignored in LINQ to SQL queries. As a result, queries that have this method might behave differently. For example, in some cases, an OrderBy clause is required with Skip(0), and the query will now throw a NotSupportedException exception if the OrderBy clause was not included.

WCF Data Services

The following table describes improvements to features that previously had limitations or other issues.

Namespaces: System.Data.Services, System.Data.Services.Client, System.Data.Services.Common, System.Data.Services.Providers

Assemblies: System.Data.Services (in System.Data.Services.dll), System.Data.Services.Client (in System.Data.Services.Client.dll)

Feature Differences from 3.5 SP1
Batched Binary Content WCF Data Services now supports batched binary content in requests and responses.
Change interceptors Change interceptors are now executed for a delete request.

A change interceptor is a method that runs every time a request is received by the server to modify an entity in the entity set. It runs before the incoming request is executed. The change interceptor provides access to the entity that is being changed and the operation that is being performed on it.
Exceptions The following conditions now throw more useful exceptions instead of a NullReferenceException:

* A TimeoutException when a call to a data service times out.
* A DataServiceRequestException when a bad request is made to a data service.

In your applications, you should change exception handling to catch the new exceptions.
Headers The following improvements were made to headers:

* WCF Data Services now correctly rejects an eTag header that has an unspecified value.
* WCF Data Services now returns an error and does not execute the request for a delete request to a link when an if-* header is in the request.
* WCF Data Services now returns an error to the client in the format (Atom, JSON) that the client specified in the Accept header.
JSON Reader The JavaScript Object Notation (JSON) reader now correctly returns an error when it reads the single backslash ("\") escape character, when it processes JSON payloads sent to a WCF Data Service.
Merges The following improvements were made to the MergeOption enumeration:

* The MergeOption merge option no longer modifies the entity on the client as a result of any subsequent response from a data service.
* The MergeOption option is now consistent between dynamic SQL and stored procedure-based updates.
Requests The OnStartProcessingRequest method is now called before a request to data services is processed. This enables the request to work correctly for ServiceOperation services.
Streams WCF Data Services no longer closes the underlying stream for read and write operations.
URIs The escaping of URIs by WCF Data Services client has been corrected.

Windows Communication Foundation (WCF)

The following table describes improvements to features that previously had limitations or other issues.

Feature Differences from 3.5 SP1
Configuration files To enable inheritance of behaviors through the configuration file hierarchy, WCF now supports merging across configuration files.

The configuration inheritance model is now expanded to let users define behaviors that will be applied to all the services that are running on the computer.

You may encounter behavioral changes if there are behaviors with the same name at different levels of the hierarchy.
Service hosting You can no longer specify the <serviceHostingEnvironment> configuration element at the service level by adding the attribute allowDefinition="MachineToApplication" to the element definition.

Specifying the <serviceHostingEnvironment> element at the service level is technically incorrect and causes inconsistent behavior.

Windows Presentation Foundation (WPF)

Applications

Namespaces: System.Windows, System.Windows.Controls

Assemblies: PresentationFramework (in PresentationFramework.dll)

Feature Differences from 3.5 SP1 Recommended changes
Exception handling To enable errors to be detected earlier, WPF throws a TargetInvocationException and sets the InnerException property to critical exceptions, such as NullReferenceException, OutOfMemoryException, StackOverflowException, and SecurityException, instead of catching the original exception. None.
Linked resources To make linking easier, resource files (such as images) that are located in a location other than the project's folder structure use the resource file's full path instead of just its file name as the resource ID when the application is built. The application will be able to locate the files at run time. None.
Partial-trust applications For security considerations, Windows-based applications that run in partial trust and contain a WebBrowser control or a Frame control that contains HTML will throw a SecurityException when the control is created.

Browser applications will throw an exception and display a message if all of the following conditions are met:

* The application is running in Firefox.
* The application is running in partial trust in the Internet zone from non-trusted sites.
* The application contains a WebBrowser control or a Frame control that contains HTML.

Applications that run from trusted sites or from the intranet zone will not be affected.
In your browser applications, you can ease this change by doing one of the following:

* Run the browser application in full trust.
* Have customers add the application's site to the trusted sites zone.
Resource dictionaries To improve theme-level resource dictionaries and prevent them from changing, freezable resources that are defined in a resource dictionary and merged into a theme-level dictionary are now always marked as frozen and are immutable. This is the expected behavior for freezable resources. Applications that modify a resource that is defined in a theme-level merged dictionary should clone the resource and modify the cloned copy. Alternatively, the resource can be marked x:Shared="false" so that the ResourceDictionary creates a new copy every time the resource is queried.
Windows 7 To make WPF applications work better on Windows 7, the following improvements were made to correct the behavior of a window:

* Dock and gesture states now work as expected based on user interactions.
* The taskbar commands Cascade windows, Show windows stacked, and Show windows side-by-side now have the correct behavior and update the appropriate properties.
* The Top, Left, Width, and Height properties for a maximized or minimized window now contain the correct restore location of the window instead of other values, depending on the monitor.
None.
Windows style and transparency An InvalidOperationException is thrown if you try to set WindowStyle to a value other than WindowStyle when AllowsTransparency is true and WindowState is WindowState. If you must change the WindowStyle when AllowsTransparency is true, you can call the Win32 SetWindowLongPtr function.
XPS Viewer WPF does not include the Microsoft XML Paper Specification Essentials Pack (XPSEP). XPSEP is included with Windows 7 and Windows Vista.

On a computer that is running Windows XP without .NET Framework 3.5 SP1 installed, printing by using a WPF API other than those in PrintDialog will rely on the WINSPOOL. Some printer capabilities will not be reported and some printer settings will not be applied during printing.
If needed, install the Microsoft XML Paper Specification Essentials Pack.

Controls

Namespaces: System.Windows, System.Windows.Controls, System.Windows.Data, System.Windows.Input

Assemblies: PresentationFramework (in PresentationFramework.dll), PresentationCore (in PresentationCore.dll), WindowsBase (in WindowsBase.dll)

Feature Differences from 3.5 SP1 Recommended changes
Dialog boxes To improve reliability, the ShowDialog method is called on the same thread that created the FileDialog control. Be sure to create a FileDialog control and call the ShowDialog method on the same thread.
Floating windows To fix focus restoration logic that incorrectly keeps reactivating a floating window (making it appear like a modal dialog box), focus restoration is now prevented if the candidate is not a child of the window. None.
Items in collections When an item is moved or added to an underlying collection, it appears in the CollectionView in the same relative location if the CollectionView is not sorted. This provides consistency between the item's position in the collection and in the associated CollectionView. Use the ContainerFromItem or IndexOf method to find the location of an item in a CollectionView instead of relying on a fixed location of an item.
Layouts To eliminate unnecessary re-layouts, changing the ShowsNavigationUI no longer invalidates layout or causes another layout pass. If you expect that changing ShowsNavigationUI will cause another layout pass, call InvalidateVisual after you set the property.
Menus To enable ClearType text in menu pop-ups, modifications were made to the ControlTemplate class and to the MenuItem control and other controls. Applications should not rely on the visual structure of control templates. Only named parts of a ControlTemplate are part of the public contract. If an application must find a certain object in a ControlTemplate, search the visual tree for a specific type instead of relying on a fixed location of an object in the tree.
Navigating If a Frame directly navigates to a location, the IsNavigationInitiator property is true after the initial navigation. This change prevents additional events from being raised during startup scenarios. None.
Pop-ups The CustomPopupPlacementCallback delegate can now be called multiple times during a layout pass instead of only once. If your CustomPopupPlacementCallback delegate calculates the position of a Popup based on its previous position, recalculate the position only if the values of the popupSize, targetSize, or offset parameters change.
Property values The SetCurrentValue method now lets you set a property to an effective value, although it continues to respect any binding, style, or trigger that affects the property. Control authors should use SetCurrentValue whenever the property value changes as a side-effect of some other action, including user manipulation.
Text boxes For security considerations, the Copy and Cut methods silently fail when they are called in partial trust.

In addition, programmatic execution of the Copy or Cut property on a control that inherits from TextBoxBase will be blocked in partial trust. However, user-initiated copy and cut commands, such as clicking a button whose Command property is bound to one of these commands, will work. Standard copy and cut through keyboard shortcuts and the context menu will still work as before in partial trust.
Bind the Copy or Cut command to a user-initiated action, such as clicking a button.

Graphics

Namespaces: System.Windows, System.Windows.Controls, System.Windows.Data, System.Windows.Input, System.Windows.Media.Effects

Assemblies: PresentationFramework (in PresentationFramework.dll), PresentationCore (in PresentationCore.dll), WindowsBase (in WindowsBase.dll)

Feature Differences from 3.5 SP1 Recommended changes
Bitmap effects To improve performance, the BitmapEffect class and the classes that inherit from the BitmapEffect class, although still present, are disabled. The effect will render by using the hardware-accelerated rendering pipeline if the following conditions are true:

* The application uses a DropShadowBitmapEffect or a BlurBitmapEffect that has a radius property set less than 100 DIU.
* The video card on the computer that runs the application supports pixel shader 2.0.

If these conditions are not met, a BitmapEffect object will have no effect.

Also, Visual Studio produces a compiler warning when it encounters the BitmapEffect object or a subclass.

The PushEffect method is marked obsolete.
Discontinue using the legacy BitmapEffect and derived classes and instead use the new classes derived from Effect: BlurEffect, DropShadowEffect, and ShaderEffect.

You can also create your own effects by inheriting from the ShaderEffect class.
Bitmap frames The cloned BitmapFrame objects now receive the DownloadProgress, DownloadCompleted, and DownloadFailed events. This enables images that are downloaded from the Web and applied to the Image control through a Style to work correctly.

You will see a change in behavior only if all of the following statements are true:

* You subscribe to the DownloadProgress, DownloadCompleted, or DownloadFailed event.
* The source of the BitmapFrame is from the Web.
* The BitmapFrame is cloned while the download is still in progress.
Check the sender in the event handler and take action only if the sender is the original BitmapFrame.
Decoding images To prevent an IOException from not being handled when images may not decode, the BitmapSource class will raise the DecodeFailed event when it does not decode an image. Remove any exception handling for IOException, and use the DecodeFailed event to check for decode failure.

Input

Namespaces: System.Windows, System.Windows.Controls, System.Windows.Data, System.Windows.Input

Assemblies: PresentationFramework (in PresentationFramework.dll), PresentationCore (in PresentationCore.dll), WindowsBase (in WindowsBase.dll)

Feature Differences from 3.5 SP1 Recommended changes
Binding command instances To provide a mechanism to bind View-Model-based command instances to View-based input gestures, the InputBinding class now inherits from Freezable instead of DependencyObject. The following properties are now dependency properties:

* Command
* CommandParameter
* CommandTarget

This change results in the following:

* An InputBinding object is now frozen when it is registered instead of remaining mutable.
* You cannot access instance-level InputBinding objects from multiple threads, due to the restrictions of the DependencyObject class.
* You cannot mutate class-level input bindings after their registration, due to the restrictions of the Freezable class.
* You cannot specify input bindings on command instances that are created in a View-Model.
Create separate instances of an InputBinding class on separate threads if bindings are to be mutable, or freeze them otherwise. Do not mutate a class-level static InputBinding after it has been registered.
Browser applications WPF Browser applications (.XBAP) now process key events just like stand-alone WPF applications so that objects receive routed key events in the correct order. None.
Dead key combinations WPF obfuscates dead keys, which produce no visible character, but instead indicates that the key is to be combined with the next letter key to produce one character. The key input events, such as the KeyDownEvent event, report when a key is a dead key by setting the Key property to the Key value. This is usually expected behavior because applications usually do not intend to respond to keyboard input that creates a combined character. Applications that expect to read keys that were part of combined characters can get the now obfuscated key by using the DeadCharProcessedKey property.
Focus manager When the FocusManager.GetFocusedElement(DependencyObject) method is passed an element that has the IsFocusScope attached property set to true, the method returns an element that is the last keyboard-focused element within that focus scope if and only if the returned element belongs to the same PresentationSource object as the element that is passed to the method. None.

UI Automation

Namespace: System.Windows, System.Windows.Automation.Peers, System.Windows.Automation.Provider, System.Windows.Controls, System.Windows.Data, System.Windows.Input

Assemblies: PresentationFramework (in PresentationFramework.dll), PresentationCore (in PresentationCore.dll), UIAutomationProvider (in UIAutomationProvider.dll), WindowsBase (in WindowsBase.dll)

Feature Differences from 3.5 SP1 Recommended changes
Class hierarchy of views The TreeViewAutomationPeer and TreeViewItemAutomationPeer classes inherit from ItemsControlAutomationPeer instead of FrameworkElementAutomationPeer. If you inherit from the TreeViewItemAutomationPeer classes and override the GetChildrenCore method, consider returning an object that inherits from the new TreeViewDataItemAutomationPeer class.
Containers off screen To fix an incorrect return value, the IsOffscreenCore method now correctly returns false for item containers that are scrolled out of view. Also, the value of the method is not affected by occlusion by other windows, or by whether the element is visible on a specific monitor. None.
Menus and child objects To enable UI automation of menus that contain children other than MenuItem objects, the GetChildrenCore method now returns the AutomationPeer object of a child UIElement object, instead of a MenuItemAutomationPeer object. None.
New interfaces and assembly To enable new features for UI automation, the following interfaces were added:

* IItemContainerProvider
* ISynchronizedInputProvider
* IVirtualizedItemProvider
Any project that builds WPF automation peers must add an explicit reference to UIAutomationProvider.dll.
Thumbs The GetClassNameCore method returns a value instead of null. Therefore, controls such as GridSplitter that inherit from the Thumb class will report a name to UI Automation. None.
Virtualized elements To improve performance, the GetChildrenCore method returns only the child objects that are actually in the visual tree, instead of all child objects, regardless of whether they are virtualized. Use ItemContainerPattern to iterate over all items of an ItemsControlAutomationPeer.

XAML

Namespaces: System.Windows, System.Windows.Controls, System.Windows.Data, System.Windows.Input, System.Windows.Markup

Assemblies: PresentationFramework (in PresentationFramework.dll), PresentationCore (in PresentationCore.dll), WindowsBase (in WindowsBase.dll)

Feature Differences from 3.5 SP1 Recommended changes
Markup extension WPF now correctly always uses the value from the ProvideValue method instead of returning the MarkupExtension object in certain cases when a markup extension is used to set a property or to create an item in a collection. A markup extension might return itself in some cases. If your application accesses a resource that returned a MarkupExtension object in earlier versions, reference the object that is returned from ProvideValue, instead of the MarkupExtension object.
Parsing attributes Attributes in XAML can now have only one period. For example, the following are valid:

<Button Background="Red"/> (no periods)

<Button Button.Background = "Red"/> (one period)

The following is no longer valid:

<Button Control.Button.Background = "Red"/> (more than one period)
Correct XAML attributes that have more than one period.

XML

The rows in this table describe improvements to features that previously had limitations or other issues.

Schema and transforms

Namespaces: System.Xml.Linq; System.Xml.Schema, System.Xml.XPath

Assemblies: System.Xml (in System.Xml.dll), System.Xml.Linq (in System.Xml.Linq.dll)

Feature Differences from 3.5 SP1
Chameleon schemas To prevent data corruption, chameleon schemas are now cloned correctly when they are included with multiple schemas.

Chameleon schemas are schemas that do not have a target namespace, and when they are included in another XSD, they take on the target namespace of the importing schema. They are often used to include common types into a schema.
ID functions The XSLT id function now returns the correct value instead of null when an XmlReader object is passed to an XLST.

If the user created an XmlReader object from a LINQ to XML class by using the CreateReader method, and this XmlReader object was passed to an XSLT, any instances of the id function in the XSLT previously returned null. This is not an allowed return value for the id function.
Namespace attribute To prevent data corruption, an XPathNavigator object now returns the local name of the x:xmlns attribute correctly.
Namespace declarations An XmlReader object on a subtree no longer creates duplicate namespace declarations within one XML element.
Schema validation To prevent erroneous schema validation, the XmlSchemaSet class allows for XSD schemas to be compiled correctly and consistently. These schemas can include other schemas; for example, A.xsd can include B.xsd, which can include C.xsd. Compiling any one of these causes this graph of dependencies to be traversed.
Script functions The function-available function no longer incorrectly returns false when the function is actually available.
URIs The Load method now returns the correct BaseURI in LINQ queries.

Validation

Namespaces: System.Xml.Linq; System.Xml.Schema, System.Xml.XPath

Assemblies: System.Xml (in System.Xml.dll), System.Xml.Linq (in System.Xml.Linq.dll)

Feature Differences from 3.5 SP1
Namespace resolvers The ReadContentAs method no longer ignores the IXmlNamespaceResolver resolver passed to it.

In previous versions, the specified namespace resolver was ignored, and the XmlReader was used instead.
White space To prevent data loss when you are creating a reader, the Create method no longer discards significant white space.

XML validation recognizes mixed-content mode, where text can be intermixed with XML markup. In mixed mode, all white space is significant and should be reported.

Writing

Namespaces: System.Xml.Linq; System.Xml.Schema, System.Xml.XPath

Assemblies: System.Xml (in System.Xml.dll), System.Xml.Linq (in System.Xml.Linq.dll)

Feature Differences from 3.5 SP1
Entity references To prevent data corruption, entity references are no longer entitized twice in XML attributes.

If the user tried to write an entity into an xmlns attribute or into an xml:lang or xml:space attribute by using the WriteEntityRef method, the entity was entitized twice in the output, therefore corrupting the data.
New line handling To prevent data corruption, XmlWriter objects respect the NewLineHandling option.

See also