Exploring the Top New Features of the CLR

0
48
9 min read

(For more resources related to this topic, see here.)

One of its most important characteristics is that it is an in-place substitution of the .NET 4.0 and only runs on Windows Vista SP2 or later systems.

.NET 4.5 breathes asynchronous features and makes writing async code even easier. It also provides us with the Task Parallel Library (TPL) Dataflow Library to help us create parallel and concurrent applications.

Another very important addition is the portable libraries, which allow us to create managed assemblies that we can refer through different target applications and platforms, such as Windows 8, Windows Phone, Silverlight, and Xbox.

We couldn’t avoid mentioning Managed Extensibility Framework (MEF), which now has support for generic types, a convention-based programming model, and multiple scopes.

Of course, this all comes together with a brand-new tooling, Visual Studio 2012, which you can find at http://msdn.microsoft.com/en-us/vstudio. Just be careful if you have projects in .NET 4.0 since it is an in-place install.

For this article I’d like to give a special thanks to Layla Driscoll from the Microsoft .NET team who helped me summarize the topics, focus on what’s essential, and showcase it to you, dear reader, in the most efficient way possible. Thanks, Layla.

There are some features that we will not be able to explore through this article as they are just there and are part of the CLR but are worth explaining for better understanding:

  • Support for arrays larger than 2 GB on 64-bit platforms, which can be enabled by an option in the app config file.
  • Improved performance on the server’s background garbage collection, which must be enabled in the <gcServer> element in the runtime configuration schema.
  • Multicore JIT: Background JIT (Just In Time) compilation on multicore CPUs to improve app performance. This basically creates profiles and compiles methods that are likely to be executed on a separate thread.
  • Improved performance for retrieving resources.
  • The culture-sensitive string comparison (sorting, casing, normalization, and so on) is delegated to the operating system when running on Windows 8, which implements Unicode 6.0. On other platforms, the .NET framework will behave as in the previous versions, including its own string comparison data implementing Unicode 5.0.

Next we will explore, in practice, some of these features to get a solid grasp on what .NET 4.5 has to offer and, believe me, we will have our hands full!

Creating a portable library

Most of us have often struggled and hacked our code to implement an assembly that we could use in different .NET target platforms. Portable libraries are here to help us to do exactly this.

Now there is an easy way to develop a portable assembly that works without modification in .NET Framework, Windows Store apps style, Silverlight, Windows Phone, and XBOX 360 applications.

The trick is that the Portable Class Library project supports a subset of assemblies from these platforms, providing us a Visual Studio template.

This article will show you how to implement a basic application and help you get familiar with Visual Studio 2012.

Getting ready

In order to use this section you should have Visual Studio 2012 installed. Note that you will need a Visual Studio 2012 SKU higher than Visual Studio Express for it to fully support portable library projects.

How to do it…

Here we will create a portable library and see how it works:

  1. First, open Visual Studio 2012 and create a new project. We will select the Portable Class Library template from the Visual C# category.
  2. Now open the Properties dialog box of our newly created portable application and, in the library we will see a new section named Target frameworks. Note that, for this type of project, the dialog box will open as soon as the project is created, so opening it will only be necessary when modifying it afterwards.

  3. If we click on the Change button, we will see all the multitargeting possibilities for our class.

  4. We will see that we can target different versions of a framework. There is also a link to install additional frameworks. The one that we could install right now is XNA but we will click on Cancel and let the dialog box be as it is.
  5. Next, we will click on the show all files icon at the top of the Solution Explorer window (the icon with two papers and some dots behind them), right-click on the References folder, and click on Add Reference. We will observe on doing so that we are left with a .NET subset of assemblies that are compatible with the chosen target frameworks.

  6. We will add the following lines to test the portable assembly:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace pcl_myFirstPcl
    {
    public static class MyPortableClass
    {
    public static string GetSomething()
    {
    return "I am a portable class library";
    }
    }
    }

  7. Build the project.
  8. Next, to try this portable assembly we could add, for example, a Silverlight project to the solution, together with an ASP.NET Web application project to wrap the Silverlight.
  9. We just need to add a reference to the portable library project and add a button to the MainPage.xaml page that calls the portable library static method we created.
  10. The code behind it should look as follows. Remember to add a using reference to our portable library namespace.

    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using pcl_myFirstPcl;
    namespace SilverlightApplication_testPCL
    {
    public partial class MainPage : UserControl
    {
    public MainPage()
    {
    InitializeComponent();
    }
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
    String something = MyPortableClass.GetSomething();
    MessageBox.Show("Look! - I got this string from my portable class
    library: " + something);
    }
    }
    }

  11. We can execute the code and check if it works.
  12. In addition, we could add other types of projects, reference the Portable Library Class, and ensure that it works properly.

How it works…

We created a portable library from the Portable Class Library project template and selected the target frameworks.

We saw the references; note that it reinforces the visibility of the assemblies that break the compatibility with the targeted platforms, helping us to avoid mistakes.

Next we added some code, a target reference application that referenced the portable class, and used it.

There’s more…

We should be aware that when deploying a .NET app that references a Portable Class Library assembly, we must specify its dependency to the correct version of the .NET Framework, ensuring that the required version is installed.

A very common and interesting usage of the Portable Class Library would be to implement MVVM. For example, we could put the View Model and Model classes inside a portable library and share it with Windows Store apps, Silverlight, and Windows Phone applications. The architecture is described in the following diagram, which has been taken from MSDN (http://msdn.microsoft.com/en-us/library/hh563947%28v=vs.110%29.aspx):

It is really interesting that the list of target frameworks is not limited and we even have a link to install additional frameworks, so I guess that the number of target frameworks will eventually grow.

Controlling the timeout in regular expressions

.NET 4.5 gives us improved control on the resolution of regular expressions so we can react when they don’t resolve on time. This is extremely useful if we don’t control the regular expressions/patterns, such as the ones provided by the users.

A badly formed pattern can have bad performance due to excessive backtracking and this new feature is really a lifesaver.

How to do it…

Next we are going to control the timeout in the regular expression, where we will react if the operation takes more than 1 millisecond:

  1. Create a new Visual Studio project of type Console Application, named caRegexTimeout.
  2. Open the Program.cs file and add a using clause for using regular expressions:

    Using System.Text.RegularExpressions;

  3. Add the following method and call it from the Main function:

    private static void ExecuteRegexExpression() {
    bool RegExIsMatch = false;
    string testString = "One Tile to rule them all, One Tile to find
    them… ";
    string RegExPattern = @"([a-z ]+)*!";
    TimeSpantsRegexTimeout = TimeSpan.FromMilliseconds(1);
    try
    {
    RegExIsMatch = Regex.IsMatch(testString, RegExPattern,
    RegexOptions.None, tsRegexTimeout);
    }
    catch (RegexMatchTimeoutException ex)
    {
    Console.WriteLine("Timeout!!");
    Console.WriteLine("- Timeout specified: " + ex.MatchTimeout);
    }
    catch (ArgumentOutOfRangeException ex)
    {
    Console.WriteLine("ArgumentOutOfRangeException!!");
    Console.WriteLine(ex.Message);
    }
    Console.WriteLine("Finished succesfully: " + RegExIsMatch.
    ToString());
    Console.ReadLine();
    }

  4. If we execute it, we will see that it doesn’t fi nish successfully, showing us some details in the console window.

  5. Next, we will change testString and RegExPattern to:

    String testString = "jose@brainsiders.com";
    String RegExPattern = @"^([w-.]+)@([w-.]+).[a-zA-Z]{2,4}$";

  6. If we run it, we will now see that it runs and fi nishes successfully.

How it works…

The RegEx.IsMatch() method now accepts a parameter, which is matchTimeout of type TimeSpan, indicating the maximum time that we allow for the matching operation. If the execution time exceeds this amount, RegexMatchTimeoutException is launched.

In our code, we have captured it with a try-catch statement to provide a custom message and of course to react upon a badly formed regex pattern taking too much time.

We have tested it with an expression that will take some more time to validate and we got the timeout. When we changed the expression to a good one with a better execution time, the timeout was not reached.

Additionally, we also watched out for the ArgumentOutOfRangeException, which is thrown when TimeSpan is zero, or negative, or greater than 24 days.

There’smore…

We could also set a global matchTimeout for the application through the “REGEX_DEFAULT_MATCH_TIMEOUT” property with the AppDomain.SetData method:

AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_
TIMEOUT",TimeSpan.FromMilliseconds(200));

Anyway, if we specify the matchTimeout parameter, we will override the global value.

Defining the culture for an application domain

With .NET 4.5, we have in our hands a way of specifying the default culture for all of our application threads in a quick and efficient way.

How to do it…

We will now define the default culture for our application domain as follows:

  1. Create a new Visual Studio project of type Console Application named caCultureAppDomain.
  2. Open the Program.cs file and add the using clause for globalization:

    using System.Globalization;

  3. Next, add the following methods:

    static void DefineAppDomainCulture() {
    String CultureString = "en-US";
    DisplayCulture();
    CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecif
    icCulture(CultureString);
    CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpec
    ificCulture(CultureString);
    DisplayCulture();
    Console.ReadLine();
    }
    static void DisplayCulture() {
    Console.WriteLine("App Domain........: {0}", AppDomain.
    CurrentDomain.Id);
    Console.WriteLine("Default Culture...: {0}", CultureInfo.
    DefaultThreadCurrentCulture);
    Console.WriteLine("Default UI Culture: {0}", CultureInfo.
    DefaultThreadCurrentUICulture);
    }

  4. Then add a call to the DefineAppDomainCulture() method.
  5. If we execute it, we will observe that the initial default cultures are null and we specify them to become the default for the App Domain.

How it works…

We used the CultureInfo class to specify the culture and the UI of the application domain and all its threads. This is easily done through the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties.

There’s more…

We must be aware that these properties affect only the current application domain, and if it changes we should control them.

LEAVE A REPLY

Please enter your comment!
Please enter your name here