Friday, March 29, 2013

What's New in the .NET Framework 4.0



What's New in the .NET Framework 4.0
.NET Framework 4


This topic contains information about key features and improvements in the .NET Framework version 4.0.
The new features and improvements in the .NET Framework 4 are following:
·         Security Changes in the .NET Framework 4.0
·         Application Compatibility and Deployment
·         Core New Features and Improvements
·         Managed Extensibility Framework
·         Parallel Computing
·         Networking
·         Web
·         Client· 

1.      Security changes in the .NET Framework 4
There have been two major changes to security in the .NET Framework version 4. Machine-wide security policy has been eliminated, although the permissions system remains in place, and security transparency has become the default enforcement mechanism. In addition, some permission operations that presented the potential for security vulnerabilities have been made obsolete.
Note: Code access security (CAS) has not been eliminated, Security policy has been eliminated from CAS, but evidence and permissions are still in effect. A few permissions have been eliminated, and transparency has simplified the enforcement of security. For a brief overview of the changes, see Summary of Changes in Code Access Security
We should be aware of the following key points:
·         Transparency separates code that runs as part of the application from code that runs as part of the infrastructure. It was introduced in .NET Framework version 2.0, and has been enhanced to become the code access security enforcement mechanism. Unlike security policy, level 2 transparency rules are enforced at run time, not at assembly load time. These rules are always in effect, even for assemblies that run as fully trusted by default. However, level 2 transparency does not affect fully trusted code that is not annotated, such as desktop applications. Assemblies (including desktop assemblies) that are marked with the SecurityTransparentAttribute and that call methods marked with the SecurityCriticalAttribute receive a MethodAccessException. You can change this behavior by applying the SecurityRulesAttribute and setting the SecurityRulesAttribute.RuleSet property to Level1; however, you should do this only for backwards compatibility. You must explicitly mark a desktop application as security-transparent to apply transparency restrictions to it.
·         Code that calls security policy APIs receives a NotSupportedException in addition to compiler warnings at run time. Policy may be re-enabled by using the <NetFx40_LegacySecurityPolicy> configuration element. When policy is enabled, security transparency is still in effect. Security policy is applied at assembly load time and has no effect on transparency, which is enforced by the runtime.
·         The obsolete request permissions (RequestMinimumRequestOptional, and RequestRefuse) receive compiler warnings and do not work in the .NET Framework 4, but they do not cause an exception to be thrown. Deny requests cause a NotSupportedException to be thrown at run time.
·         The LinkDemand security action is not obsolete, but it should not be used for verifying permissions. Instead, use the SecurityCriticalAttribute for types and methods that require full trust, or use the Demand method for types and methods that require individual permissions.
·         If your application is built with Visual Studio 2010, you can run it without these changes by specifying a target .NET Framework version that is earlier than the .NET Framework 4 in the Visual Studio project settings. However, you will not be able to use new .NET Framework 4 types and members. You can also specify an earlier version of the .NET Framework by using the <supportedRuntime> element in the startup settings schema in your application configuration file.
The following sections discuss these and other changes in the .NET Framework 4: 
  1. Security Policy Simplification
  2. Security Transparency Level 2
  3. Obsolete Permission Requests
  4. Conditional APTCA
  5. Evidence Objects
  6. Evidence Collections
A. Security Policy Simplification
Starting with the .NET Framework 4, the common language runtime (CLR) is moving away from providing security policy for computers. Historically, the .NET Framework has provided code access security (CAS) policy as a mechanism to tightly control and configure the capabilities of managed code. Although CAS policy is powerful, it can be complicated and restrictive. Furthermore, CAS policy does not apply to native applications, so its security guarantees are limited. System administrators should look to operating system-level solutions such as Windows Software Restriction Policies (SRP) or AppLocker on Windows 7 and Windows Server 2008 R2 as a replacement for CAS policy. SRP and AppLocker policies provide simple trust mechanisms that apply to both managed and native code. As a security policy solution, SRP and AppLocker are simpler and provide better security guarantees than CAS.
In the .NET Framework 4, machine-wide security policy is turned off by default. Applications that are not hosted (that is, applications that are executed through Windows Explorer or from a command prompt) now run as full trust. This includes all applications that reside on shares on the local network. Hosted or sandboxed applications continue to run with trust policies that are decided by their hosts (for example, by Internet Explorer, ClickOnce, or ASP.NET). Applications or controls that run in sandboxes are considered partially trusted.
To simplify the security policy, the transparency model has been applied to the .NET Framework. Applications and controls that run in a host or sandbox with the limited permission set granted by the sandbox are considered transparent. Transparency means that you do not have to be concerned about checking CAS policy when you are running partially trusted applications. Transparent applications just run using their grant set. As a programmer, your only concern should be that your applications target the grant set for their sandbox and that they do not call code that requires full trust (security-critical code).
Note: As a result of these security policy changes, you may encounter compilation warnings and runtime exceptions if you call the obsolete CAS policy types and members either explicitly or implicitly (through other types and members). For a list of obsolete types and members and their replacements, see Code Access Security Policy Compatibility and Migration.
You can avoid the warnings and errors by using the <NetFx40_LegacySecurityPolicy> configuration element in the runtime settings schema to opt into the legacy CAS policy behavior. However, specifying the use of legacy security policy does not include any custom CAS policy for that version unless it is migrated to .NET Framework 4.
You can also enable legacy CAS policy by setting the target .NET Framework version for your Visual Studio project to an earlier version than the .NET Framework 4. This enables legacy CAS policy and includes any custom CAS policies you specified for that version. However, you will not be able to use new .NET Framework 4 types and members. You can also specify an earlier version of the .NET Framework by using the <supportedRuntime> element in the startup settings schema.

B. Security Transparency Level 2
Security transparency was introduced in the .NET Framework version 2.0, but it was very limited and used primarily to improve code validation efficiency. In the .NET Framework 4, transparency is an enforcement mechanism that separates code that runs as part of the application from code that runs as part of the infrastructure. Transparency draws a barrier between code that can do privileged things (critical code), such as calling native code, and code that cannot (transparent code). Transparent code can execute commands within the bounds of the permission set it is operating within, but cannot execute, call, derive from, or contain critical code.
The primary goal of transparency enforcement is to provide a simple, effective mechanism for isolating different groups of code based on privilege. In the sandboxing model, these privilege groups are either fully trusted (that is, not restricted) or partially trusted (that is, restricted to the permission set granted to the sandbox).
Desktop applications run as fully trusted; therefore, they are not affected by the transparency model.

C. Obsolete Permission Requests
Runtime support has been removed for enforcing the DenyRequestMinimumRequestOptional, and RequestRefuse permission requests. In general, these requests were not well understood and presented the potential for security vulnerabilities when they were not used properly:
·         Deny action could be easily overridden by an Assert action. The code in an assembly was able to execute an Assert action for a permission if the permission was in the grant set for the assembly. The Assert prevented the Deny from being seen on the stack, making it ineffective.
·         RequestMinimum could not be used effectively outside the application scope. If RequestMinimum appeared on an executable (.exe) file and the grant set was not met, end users of the file received an unhandled FileLoadException exception that contained no information about how to correct the problem. You could not use a single minimum request set for libraries (.dll files), because different types and members in the assembly generally have different permission requirements.
·         RequestOptional was confusing and often used incorrectly with unexpected results. Developers could easily omit permissions from the list without realizing that doing so implicitly refused the omitted permissions.
·         RequestRefuse did not provide an effective least-privilege model, because it required you to explicitly identify permissions you did not want instead of identifying the permissions you needed. In addition, if new permissions became available, they would not be included in the list. Furthermore, refusal did not make sense for all permissions. For example, you could refuse a value for the UserQuota property in the IsolatedStoragePermission.
Finally, specifying only the permissions you did not want created the potential for security vulnerabilities if you failed to identify all potentially harmful permissions.
·         RequestOptional and RequestRefuse enabled developers to break homogenous domains by creating multiple permission sets within the domain.
The .NET Framework 4 removes runtime enforcement of these enumeration values. Assemblies containing the attributes that use these SecurityAction values will continue to load; however, the CLR will not refuse to load the referenced assemblies or modify their grant set based upon the permission sets.

D. Conditional APTCA
The conditional use of the AllowPartiallyTrustedCallersAttribute (APTCA) attribute enables hosts to identify which assemblies they want to expose to partial-trust callers that are loaded within the context of the host. The candidate assemblies must already be designed for partial trust; that is, they must either be APTCA (security-safe-critical in the transparency model) or fully transparent. A new constructor for the AllowPartiallyTrustedCallersAttribute enables the host to specify the level of visibility for an APTCA assembly by using the PartialTrustVisibilityLevel enumeration in the constructor call.

E. Evidence Objects
Before the .NET Framework 4, almost any object could be used as an evidence object if the hosting code wanted to apply it as evidence. For example, some .NET Framework code recognized System.Uri objects as evidence. The runtime considered evidence objects as System.Object references and did not apply any type safety to them.
This presented a problem because the .NET Framework imposed implicit restrictions on which types could be used as evidence objects. Specifically, any object used as evidence had to be serializable and could not be null. If these requirements were not met, the CLR threw an exception whenever an operation that required one of these assumptions was performed.
To enable constraints on the types of objects that can be used as evidence and to provide the ability to add new features and requirements to all evidence objects, the .NET Framework 4 introduces a new base class, System.Security.Policy.EvidenceBase, which all evidence objects must derive from. The EvidenceBase class ensures, upon instantiation, that the evidence object is serializable. In addition, new evidence requirements can be created in the future by adding new default implementations to the base class.

Backward Compatibility
All the types used by the CLR as evidence objects have been updated in the .NET Framework 4 to derive from EvidenceBase. However, custom evidence types used by third-party applications are not known and cannot be updated. Therefore, those evidence types cannot be used with the new members that expect evidence derived from EvidenceBase

F. Evidence Collections
Before the .NET Framework 4, the CLR generated the full set of evidence objects that applied to an assembly when the assembly was loaded. These objects were stored in a list, which consumers would then iterate over looking for a specific object. Therefore, all evidence was made available, whether or not it was used. For most evidence objects, this behavior was not an issue; however, for evidence objects such as System.Security.Policy.Publisher (which requires Authenticode verification), this behavior was inefficient.
To improve this behavior, the interaction with the evidence collection has been redesigned in .NET Framework 4. An evidence collection now behaves like a dictionary instead of a list. Instead of iterating over the evidence collection to see if a required evidence object exists, consumers can now request a specific type of evidence, and the collection returns the evidence if it is found. For example, the call StrongName name = evidence.GetHostEvidence<StrongName>(); returns a StrongName object if one exists; otherwise, it returns null.
This dictionary model delays the generation of evidence objects until they are requested. In the Publisher evidence example, the performance overhead of verifying the Authenticode signature of an assembly is delayed until that information is needed. In the most common case of full-trust applications where Publisher evidence is not needed, the verification process is avoided altogether.


2.    Application Compatibility and Deployment
The .NET Framework 4 is highly compatible with applications that are built with earlier .NET Framework versions, except for some changes that were made to improve security, standards compliance, correctness, reliability, and performance.
The .NET Framework 4 does not automatically use its version of the common language runtime to run applications that are built with earlier versions of the .NET Framework. To run older applications with .NET Framework 4, you must compile your application with the target .NET Framework version specified in the properties for your project in Visual Studio, or you can specify the supported runtime with the <supportedRuntime> Element in an application configuration file.
The following sections describe deployment improvements.

Client Profile
The .NET Framework 4 Client Profile supports more platforms than in previous versions and provides a fast deployment experience for your applications. Several new project templates now target the Client Profile by default.

In-Process Side-by-Side Execution
This feature enables an application to load and start multiple versions of the .NET Framework in the same process. For example, you can run applications that load add-ins (or components) that are based on the .NET Framework 2.0 SP1 and add-ins that are based on the .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.
3.        Core New Features and Improvements
The following sections describe new features and improvements provided by the common language runtime and the base class libraries.

Diagnostics and Performance
Earlier versions of the .NET Framework provided no way to determine whether a particular application domain was affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4, you can get processor usage and memory usage estimates per application domain.
You can monitor CPU and memory usage of individual application domains. Application domain resource monitoring is available through the managed and native hosting APIs and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process. See the new AppDomain.MonitoringIsEnabled property.
You can now access the ETW events for diagnostic purposes to improve performance.
The System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute attribute enables managed code to handle exceptions that indicate corrupted process state.

Globalization
The .NET Framework 4 provides new neutral and specific cultures, updated property values, improvements in string handling, and other improvements.

Garbage Collection
The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance.

Code Contracts
Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of preconditions, postconditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and support documentation generation.

Design-Time-Only Interop Assemblies
You no longer have to ship primary interop assemblies (PIAs) to deploy applications that interoperate with COM objects. In the .NET Framework 4, compilers can embed type information from interop assemblies, selecting only the types that an application (for example, an add-in) actually uses. Type safety is ensured by the common language runtime. See Using COM Types in Managed Code and Walkthrough: Embedding Type Information from Microsoft Office Assemblies (C# and Visual Basic).

Dynamic Language Runtime
The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework.
The expression trees are extended with new types that represent control flow, for example, System.Linq.Expressions.LoopExpression and System.Linq.Expressions.TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.
In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace.

Covariance and Contravariance
Several generic interfaces and delegates now support covariance and contravariance.

BigInteger and Complex Numbers

The new System.Numerics.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.
The new System.Numerics.Complex structure represents a complex number that supports arithmetic and trigonometric operations with complex numbers.

Tuples
The .NET Framework 4 provides the System.Tuple class for creating tuple objects that contain structured data. It also provides generic tuple classes to support tuples that have from one to eight components (that is, singletons through octuples). To support tuple objects that have nine or more components, there is a generic tuple class with seven type parameters and an eighth parameter of any tuple type
File System Enumeration Improvements
New file enumeration methods improve the performance of applications that access large file directories or that iterate through the lines in large files.

Memory-Mapped Files
The .NET Framework now supports memory-mapped files. You can use memory-mapped files to edit very large files and to create shared memory for interprocess communication.

64-Bit Operating Systems and Processes
You can identify 64-bit operating systems and processes with the Environment.Is64BitOperatingSystem and Environment.Is64BitProcess properties.
You can specify a 32-bit or 64-bit view of the registry with the Microsoft.Win32.RegistryView enumeration when you open base keys.

Other New Features
The following list describes additional new capabilities, improvements, and conveniences. Several of these are based on customer suggestions.
·         To support culture-sensitive formatting, the System.TimeSpan structure includes new overloads of the ToString, Parse, and TryParse methods, as well as new ParseExact and TryParseExact methods.
·         The new String.IsNullOrWhiteSpace method indicates whether a string is null, empty, or consists only of white-space characters. New overloads have been added to the String.Concat and String.Join methods that concatenate members of System.Collections.Generic.IEnumerable(Of T) collections.
·         The String.Concat method lets you concatenate each element in an enumerable collection without first converting the elements to strings.
·         Two new convenience methods are available: StringBuilder.Clear and Stopwatch.Restart.
·         The new Enum.HasFlag method determines whether one or more bit fields or flags are set in an enumeration value. The Enum.TryParse method returns a Boolean value that indicates whether a string or integer value could be successfully parsed.
·         The System.Environment.SpecialFolder enumeration contains several new folders.
·         You can now easily copy one stream into another with the CopyTo method in classes that inherit from the System.IO.Stream class.
·         New Path.Combine method overloads enable you to combine file paths.
·         The new System.IObservable(Of T) and System.IObserver(Of T) interfaces provide a generalized mechanism for push-based notifications.
·         The System.IntPtr and System.UIntPtr classes now include support for the addition and subtraction operators.
·         You can now enable lazy initialization for any custom type by wrapping the type inside a System.Lazy(Of T) class.
·         The new System.Collections.Generic.SortedSet(Of T) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic.ISet(Of T) interface.
·         The compression algorithms for the System.IO.Compression.DeflateStream and System.IO.Compression.GZipStream classes have improved so that data that is already compressed is no longer inflated. Also, the 4-gigabyte size restriction for compressing streams has been removed.
·         The new Monitor.Enter(Object, Boolean) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
·         You can use the Thread.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.
·         The System.Guid structure now contains the TryParse and TryParseExact methods.
·         The new Microsoft.Win32.RegistryOptions enumeration lets you specify a volatile registry key that does not persist after the computer restarts.
·         Registry keys are no longer restricted to a maximum length of 255 characters.

4.     Managed Extensibility Framework
The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4 that helps you build extensible and composable applications. MEF enables you to specify points where an application can be extended, to expose services to offer to other extensible applications and to create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts.

5.      Parallel Computing
The .NET Framework 4 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new System.Threading.Tasks namespace and other related types support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax.

6.    Networking
Networking improvements include the following:
·         Security improvements for Windows authentication in several classes, including System.Net.HttpWebRequestSystem.Net.HttpListenerSystem.Net.Mail.SmtpClientSystem.Net.Security.SslStream, and System.Net.Security.NegotiateStream. Extended protection is available for applications on Windows 7 and Windows Server 2008 R2.
·         Support for Network Address Translation (NAT) traversal using IPv6 and Teredo.
·         New networking performance counters that provide information about HttpWebRequest objects.
·         In the System.Net.HttpWebRequest class, support for using large byte range headers (64-bit ranges) with new overloads for the AddRange method. New properties on the System.Net.HttpWebRequest class allow an application to set many HTTP headers. You can use the Host property to set the Host header value in an HTTP request that is independent from the request URI.
·         Secure Sockets Layer (SSL) support for the System.Net.Mail.SmtpClient and related classes.
·         Improved support for mail headers in the System.Net.Mail.MailMessage class.
·         Support for a null cipher for use in encryption. You can specify the encryption policy by using the System.Net.ServicePointManager class and the EncryptionPolicy property. Constructors for the System.Net.Security.SslStream class now take a System.Net.Security.EncryptionPolicy class as a parameter.
·         Credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication in the System.Net.NetworkCredential class. To improve security, passwords may now be treated as System.Security.SecureString instances rather than System.String instances.
·         Ability to specify how a URI with percent-encoded values is converted and normalized in the System.Uri and System.Net.HttpListener classes.

7.     Web
ASP.NET version 4 introduces new features in the following areas:
·         Core services, including a new API that lets you extend caching, support for compression for session-state data, and a new application preload manager (autostart feature).
·         Web Forms, including more integrated support for ASP.NET routing, enhanced support for Web standards, updated browser support, new features for data controls, and new features for view state management.
·         Web Forms controls, including a new Chart control.
·         MVC, including new helper methods for views, support for partitioned MVC applications, and asynchronous controllers.
·         Dynamic Data, including support for existing Web applications, support for many-to-many relationships and inheritance, new field templates and attributes, and enhanced data filtering.
·         Microsoft Ajax, including additional support for client-based Ajax applications in the Microsoft Ajax Library.
·         Visual Web Developer, including improved IntelliSense for JScript, new auto-complete snippets for HTML and ASP.NET markup, and enhanced CSS compatibility.
·         Deployment, including new tools for automating typical deployment tasks.
·         Multi-targeting, including better filtering for features that are not available in the target version of the .NET Framework.

8.     Client
Windows Presentation Foundation (WPF) version 4 contains changes and improvements in the following areas:
·         New controls, including CalendarDataGrid, and DatePicker.
·         VisualStateManager supports changing states of controls.
·         Touch and Manipulation enables you to create applications that receive input from multiple touches simultaneously on Windows 7.
·         Graphics and animation supports layout rounding, Pixel Shader version 3.0, cached composition, and easing functions.
·         Text has improved text rendering and supports customizing the caret color and selection color in text boxes.
·         Binding is supported on the Command property of an InputBinding, dynamic objects, and the Text property.
·         XAML browser applications (XBAPs) support communication with the Web page and support full-trust deployment.
·         New types in the System.Windows.Shell namespace enable you to communicate with the Windows 7 taskbar and pass data to the Windows shell.
·         The WPF and Silverlight Designer in Visual Studio 2010 has various designer improvements to help create WPF or Silverlight applications.
Google