Category Archives: 2666

C# 5.0 Async/Await Demo Code

I’ve published the sample code I use to demonstrate the use of async/await in C# 5.0. You can find it here.

Projects

PauloMorgado.AyncDemo.WebServer

This project is a simple web server implemented as a console application using Microsoft ASP.NET Web API self hosting and serves an image (with a delay) that is accessed by the other projects.

This project has a dependency on Json.NET due to the fact the the Microsoft ASP.NET Web API hosting has a dependency on Json.NET.

The application must be run on a command prompt with administrative privileges or a urlacl must be added to allow the use of the following command:

netsh http add urlacl url=http://+:9090/ user=machine\username


To remove the urlacl, just use the following command:



netsh http delete urlacl url=http://+:9090/


PauloMorgado.AsyncDemo.WindowsForms



This Windows Forms project contains three regions that must be uncommented one at a time:



Sync with WebClient



This code retrieves the image through a synchronous call using the WebClient class.



Async with WebClient



This code retrieves the image through an asynchronous call using the WebClient class.



Async deadlock



This code how async operations can still deadlock.



Async with HttpClient with cancelation



This code retrieves the image through an asynchronous call with cancelation using the HttpClient class.



PauloMorgado.AsyncDemo.Wpf



This WPF project contains three regions that must be uncommented one at a time:



Sync with WebClient



This code retrieves the image through a synchronous call using the WebClient class.



Async with WebClient



This code retrieves the image through an asynchronous call using the WebClient class.



Async deadlock



This code how async operations can still deadlock.



Async with HttpClient with cancelation



This code retrieves the image through an asynchronous call with cancelation using the HttpClient class.

Breaking Changes In Argument List Evaluation In C# 5.0

The C# Language Specification states on §7.5.1.2 that “(…) the expressions or variable references of an argument list are evaluated in order, from left to right (…)”.

So, when this code is compiled with the C# 4.0 compiler:

static void M(
    int x = 10,
    int y = 20,
    int z = 30)
{
    Console.WriteLine(
        "x={0}, y={1}, z={2}", x, y, z);
}

static void Main(string[] args)
{
    int a = 0;

    M(++a, z: ++a);
}


and run, this unexpected output is obtained:



x=2, y=20, z=1


In fact, fixing this compiler flaw was the cause of one of the few breaking changes introduced in C# 5.0.



Using the 5.0 compiler, the expected result is obtained:



x=1, y=20, z=2


To avoid this type of surprises, expression evaluation should be avoided in argument lists.



With this code:



int a = 0;

int i = ++a;
int j = ++a;

M(i, z: j);


the same result is obtained for both C# 4.0 and C# 5.0:



x=1, y=20, z=2

Hash Function Added To The PredicateEqualityComparer

Sometime ago I wrote a predicate equality comparer to be used with LINQ’s Distinct operator.

The Distinct operator uses an instance of an internal Set class to maintain the collection of distinct elements in the source collection which in turn checks the hash code of each element (by calling the GetHashCode method of the equality comparer) and only if there’s already an element with the same hash code in the collection calls the Equals method of the comparer to disambiguate.

At the time I provided only the possibility to specify the comparison predicate, but, in some cases, comparing a hash code instead of calling the provided comparer predicate can be a significant performance improvement, I’ve added the possibility to had a hash function to the predicate equality comparer.

You can get the updated code from the PauloMorgado.Linq project on CodePlex,

Globalization, Localization And Why My Application Stopped Launching

When I was localizing a Windows Phone application I was developing, I set the argument on the constructor of the AssemblyCultureAttribute for the neutral culture (en-US in this particular case) for my application.


As it was late at night (or early in the dawn Smile) I went to sleep and, on the next day, the application wasn’t launching although it compiled just fine.


I’ll have to confess that it took me a couple of nights to figure out what I had done to my application.


Have you figured out what I did wrong?


The documentation for the AssemblyCultureAttribute states that:


The attribute is used by compilers to distinguish between a main assembly and a satellite assembly. A main assembly contains code and the neutral culture’s resources. A satellite assembly contains only resources for a particular culture, as in [assembly:AssemblyCultureAttribute("de")]. Putting this attribute on an assembly and using something other than the empty string (“”) for the culture name will make this assembly look like a satellite assembly, rather than a main assembly that contains executable code. Labeling a traditional code library with this attribute will break it, because no other code will be able to find the library’s entry points at runtime.


So, what I did was marking the once main assembly as a satellite assembly for the en-US culture which made it impossible to find its entry point.


To set the the neutral culture for the assembly resources I should haveused (and eventually did) the NeutralResourcesLanguageAttribute. According to its documentation:


The NeutralResourcesLanguageAttribute attribute informs the ResourceManager of the application’s default culture, and also informs the ResourceManager that the default culture’s resources are found in the main application assembly. When looking up resources in the same culture as the default culture, the ResourceManager automatically uses the resources located in the main assembly instead of searching for a satellite assembly. This improves lookup performance for the first resource you load, and can reduce your working set.

Announcing The Microsoft Roslyn CTP

The Roslyn team has announced general availability of the Roslyn CTP!

The official launch is at http://msdn.com/roslyn, and there were a number of blogs to publicize the availability broadly (soma, ericli, vsteam, vbteam, c#faq) and across twitter.

This release marks a significant step to the new way of thinking of compilers, and the agility that is now possible with language innovation, IDE tooling, and powering the ecosystem. The C# and VB compilers are no longer black boxes – something we put source text into, do some magic on, and get an assembly out.  All that rich information about code is no longer thrown away, but is now exposed as a full-fidelity object model that can be easily consumed by all.  In addition, it was released a preview of the first-ever Interactive window for C# that contains full IDE support – including IntelliSense and even automatically detecting missing using directives.

How to get started:

  • Download the CTP.  The CTP installs on Visual Studio 2010 SP1 and can be safely installed side-by-side with Visual Studio 11.
  • Go to Start -> All Programs ->  Microsoft Codename Roslyn CTP -> Getting Started to launch the entry point into all the documentation, samples, and tools.
  • Read the Roslyn Project Overview for a good overview of the project.
  • Learn from the rich samples included (paste as C#/VB, refactorings, code analysis, and code generation tools).
  • Run the walkthroughs to learn about the Compiler APIs, the Services API, or using the Interactive window.
  • For those of you that aren’t extension writers, download the CTP to try out the Interactive window and use the Copy Paste C#/VB extensions that were built to help with your daily work now!

The release includes the following features:

  • Visual Studio Project Templates
    These project templates help you get started using the Roslyn APIs and building new Visual Studio extensions using the C# or VB APIs.
  • Reference Assemblies
    The Roslyn assemblies can be added to projects via the Add Reference dialog.
  • Interactive Window
    A new tool window called C# Interactive is available in Visual Studio by invoking View -> Other Windows -> C# Interactive from the menu. You can explore by either executing snippets of code in the C# Interactive tool window, or cumulatively building up execution context as you experiment.
  • Script File Editing Support
    C# Script (.csx) files allow top-level statements much like the C# Interactive window. You can create a new C# Script file by invoking File -> New File -> Script -> Visual C# Script from the Visual Studio menu. In addition to typing directly into the tool window, you can also select code in C# and C# Script (.csx) files and invoke "Execute in Interactive" or "Copy to Interactive" from the context menu. C# Script editing features like IntelliSense are powered by the Roslyn Language Service.

Please keep in mind that this is only a technology preview, and it’s not done yet! The primary goal of this CTP is to gather feedback on the public APIs and give an early look at the Interactive window feature. The shape of the APIs are in a fairly stable state, especially the Compiler ones, but there are still a set of known limitations and only a subset of the C# and Visual Basic languages are implemented in the current release.  For a full list of non-implemented language features, see here. The Interactive window is only available for C# at this time, but VB is following shortly.

The Roslyn team looks forward to hearing your feedback on the forums e through Connect.

What Is The .NET Framework 4.5?

According to the .NET Blog, .NET Framework 4.5 is an in-place update that replaces .NET Framework 4.0 (rather than a side-by-side installation). The goal is for .NET 4.5 to be fully backward compatible with applications built for .NET 4.0 (.NET 3.5 and .NET 4.5 will be side-by-side).

One of the first things you’ll notice about .NET 4.5 is the version number of the CLR (4.0.30319) is the same as .NET 4.0; this is the practice used by other in-place updates. (read more)

In fact, if you compare a system with .NET 4.5 with a system with .NET 4.0 you’ll see that 4.5 is just an update to 4.0:

Registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full
Value .NET 4.0 .NET 4.5
Version 4.0.30319 4.5.40805
CBS 1 1
TargetVersion 4.0.0 4.0.0
Install 1 1
Servicing 0 0
Release   368485
InstallPath C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ C:\Windows\Microsoft.NET\Framework64\v4.0.30319\

One of the major additions to the framework is the support for the Task-based Asynchronous Pattern. All classes with asynchronous APIs have be augmented with a Task-based asynchronous API.

Task exception handling has also changed in .NET 4.5 to accommodate the new async keywords in C# and VB. (read more)

Cleaning HTML With Regular Expressions

While participating in a forum discussion, the need to clean up HTML from “dangerous” constructs came up.

In the present case it was needed to remove SCRIPT, OBJECT, APPLET, EMBBED, FRAMESET, IFRAME, FORM, INPUT, BUTTON and TEXTAREA elements (as far as I can think of) from the HTML source. Every event attribute (ONEVENT) should also be removed keep all other attributes, though.

HTML is very loose and extremely hard to parse. Elements can be defined as a start tag (<element-name>) and an end tag (</element-name>) although some elements don’t require the end tag. If XHTML is being parsed, elements without an end tag require the tag to be terminated with /> instead of just >.

Attributes are not easier to parse. By definition, attribute values are required to be delimited by quotes () or double quotes (), but some browsers accept attribute values without any delimiter.

We could build a parser, but then it will become costly to add or remove elements or attributes. Using a regular expression to remove unwanted elements and attributes seems like the best option.

First, lets capture all unwanted elements with start and end tags. To capture these elements we must:

  • Capture the begin tag character followed by the element name (for which we will store its name – t): <(?<t>element-name)
  • Capture optional white spaces followed by any character: (\s+.*?)?
  • Capture the end tag character: >
  • Capture optional any characters: .*?
  • Capture the begin tag character followed by closing tag character, the element name (referenced by the name – t) and the end tag character: </\k<t>>
<(?<t>tag-name(\s+.*?)?>.*?</\k<t>>

To capture all unwanted element types, we end up with the following regular expression:

<(?<t>script|object|applet|embbed|frameset|iframe|form|textarea)(\s+.*?)?>.*?</\k<t>>

Next, lets capture all unwanted elements without an end tag. To capture these elements we must:

  • Capture the begin tag character followed by the element name: <element-name
  • Capture optional white spaces followed by any character: (\s+.*?)?
  • Capture an optional closing tag character: /?
  • Capture the end tag character: >
<tag-name(\s+.*?)?/?>

To capture all unwanted element types, we end up with the following regular expression:

<(script|object|applet|embbed|frameset|iframe|form|textarea|input|button)(\s+.*?)?/?>

To remove those unwanted elements from the source HTML, we can combine these two previous regular expressions into one and replace any match with an empty string:

Regex.Replace(
    sourceHtml,
    "|(<(?<t>script|object|applet|embbed|frameset|iframe|form|textarea)(\\s+.*?)?>.*?</\\k<t>>)"
        + "|(<(script|object|applet|embbed|frameset|iframe|form|input|button|textarea)(\\s+.*?)?/?>)"    ,
string.Empty);

And finally, the unwanted attributes. This one is trickier because we want to capture unwanted attributes inside an element’s start tag. To achieve that, we need to match an element’s opening tag and capture all attribute definitions. To capture these attributes we must:

  • Match but ignore the begin tag character followed by any element name: (?<=<\w+)
  • Match all:
    • Don’t capture mandatory with spaces: (?:\s+)
    • Capture attribute definition:
      • Capture mandatory attribute name: \w+
      • Capture mandatory equals sign: =
      • Capture value specification in one of the forms:
        • Capture double quoted value: “[^"]*”
        • Capture single quoted value: ‘[^']*’
        • Capture unquoted value: .*?
  • Match but ignore end tag: (?=/?>)
(?<=<\w+)((?:\s+)(\w+=(("[^"]*")|('[^']*')|(.*?)))*(?=/?>)

The problem with the previous regular expression is that it matches the start tag and captures the whole list of attributes and not each unwanted attribute by itself. This prevents us from from replacing each match with a fixed value (empty string).

To solve this, we have to name what we want to capture and use the Replace overload that uses a MatchEvaluator.

We could capture unwanted attributes as we did for the unwanted elements, but then we would need to remove them from the list of all the element’s attributes. Instead, we’ll capture the wanted attributes and build the list of attributes. To identify the wanted attributes, we’ll need to name them (a). The resulting code will be something like this:

Regex.Replace(
    sourceHtml,
    "((?<=<\\w+)((?:\\s+)((?:on\\w+=((\"[^\"]*\")|('[^']*')|(.*?)))|(?<a>(?!on)\\w+=((\"[^\"]*\")|('[^']*')|(.*?)))))*(?=/?>))",
    match =>
    {
        if (!match.Groups["a"].Success)
        {
            return string.Empty;
        }
        
        var attributesBuilder = new StringBuilder();
        
        foreach(Capture capture in match.Groups["a"].Captures)
        {
            attributesBuilder.Append(' ');
            attributesBuilder.Append(capture.Value);
        }
        
        return attributesBuilder.ToString();
    }
);

To avoid parsing the source HTML more than once, we can combine all the regular expressions into a single one.

Because we are still outputting only the wanted attributes, there’s no change to the match evaluator.

A few options (RegexOptions) will also be added to increase functionality and performance:

  • IgnoreCase: For case-insensitive matching.
  • CultureInvariant: For ignoring cultural differences in language.

  • Multiline: For multiline mode.

  • ExplicitCapture: For capturing only named captures.

  • Compiled: For compiling the regular expression into an assembly. Only if the regular expression is to be used many times.


The resulting code will be this:


Regex.Replace(
    sourceHtml,
    "(<(?<t>script|object|applet|embbed|frameset|iframe|form|textarea)(\\s+.*?)?>.*?</\\k<t>>)"
        + "|(<(script|object|applet|embbed|frameset|iframe|form|input|button|textarea)(\\s+.*?)?/?>)"
        + "|((?<=<\\w+)((?:\\s+)((?:on\\w+=((\"[^\"]*\")|('[^']*')|(.*?)))|(?<a>(?!on)\\w+=((\"[^\"]*\")|('[^']*')|(.*?)))))*(?=/?>))",
    match =>
    {
        if (!match.Groups["a"].Success)
        {
            return string.Empty;
        }
        
        var attributesBuilder = new StringBuilder();
        
        foreach(Capture capture in match.Groups["a"].Captures)
        {
            attributesBuilder.Append(' ');
            attributesBuilder.Append(capture.Value);
        }
        
        return attributesBuilder.ToString();
    },
    RegexOptions.IgnoreCase
        | RegexOptions.Multiline
        | RegexOptions.ExplicitCapture
        | RegexOptions.CultureInvariant
        | RegexOptions.Compiled
);

This was not extensively tested and there might be some wanted HTML remove and some unwanted HTML kept, but it’s probably very close to a good solution.

.NET Reflector 7 Released

This new version fixes a number of bugs and adds support for more high level C# features such as iterator blocks.

A new tabbed browsing model was added and Jason Haley’s PowerCommands add-in was included as an exploratory step for future versions.

To find out more about version 7 just visit http://www.reflector.net/.

The release of version 7 also means that the free version of .NET Reflector is no longer available for download. Maybe you can still get one of the give away licenses that Red Gate provided to communities and individuals.

Visual Studio 2010 Service Pack 1 And .NET Framework 4.0 Update

As announced by Jason Zender in his blog post, Visual Studio 2010 Service Pack 1 is available for download for MSDN subscribers since March 8 and is available to the general public since March 10.

Brian Harry provides information related to TFS and S. "Soma" Somasegar provides information on the latest Visual Studio 2010 enhancements.

With this service pack for Visual Studio an update to the .NET Framework 4.0 is also released.

For detailed information about these releases, please refer to the corresponding KB articles:

Update:

When I was upgrading from the Beta to the final release on Windows 7 Enterprise 64bit, the instalation hanged with Returning IDCANCEL. INSTALLMESSAGE_WARNING [Warning 1946.Property 'System.AppUserModel.ExcludeFromShowInNewInstall' for shortcut 'Manage Help Settings - ENU.lnk' could not be set.]. Canceling the installation didn’t work and I had to kill the setup.exe process.

When reapplying it again, rollbacks were reported, so I reapplied it again – this time with succes.