CodeProject

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)

Internet Explorer 10 User Agent Strings On Windows 8 64bit

Internet Explorer 10 is the web browser Microsoft is delivering with Windows 8.

According to its different usages and modes, its user agent string is as follows:

Application Environment 32/64 bit User Agent String
Internet Explorer Metro - Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)
Javascript Application Metro - Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0;)
C#/VB Application Metro 32bit Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
C#/VB Application Metro 64bit Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)
Internet Explorer Desktop 32bit
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Internet Explorer Desktop 64bit(1) Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)
WPF Application Desktop 32bit Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; Tablet PC 2.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Zune 4.7; InfoPath.3)
WPF Application Desktop 64bit Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; Win64; x64; Trident/6.0; .NET4.0E; .NET4.0C; Tablet PC 2.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Zune 4.7; InfoPath.3)
(1) Needs to be enabled for each security zone.

Analyzing the above table I conclude that:

  1. Metro Internet Explorer is always a 64bit application on 64bit Windows 8.
  2. Javascript Metro Style Applications don’t announce if they are 32bit or 64bit.
    1. They look like they are running on a 32bit Windows 8.
  3. Desktop Internet Explorer retains the same behavior introduced with Internet Explorer 8.
  4. Metro Style C#/VB Applications hosting the web browser (WebView control) exhibit the same behavior as Internet Explorer.
  5. Desktop WPF Applications hosting the web browser (WebBrowser control) retain the same behavior introduced with Internet Explorer 8.

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.

Creating Property Set Expression Trees In A Developer Friendly Way

LINQ With C# (Portuguese)In a previous post I showed how to create expression trees to set properties on an object.

The way I did it was not very developer friendly. It involved explicitly creating the necessary expressions because the compiler won’t generate expression trees with property or field set expressions.

Recently someone contacted me the help develop some kind of command pattern framework that used developer friendly lambdas to generate property set expression trees.

Simply putting, given this entity class:

public class Person
{
    public string Name { get; set; }
}

The person in question wanted to write code like this:

var et = Set((Person p) => p.Name = "me");

Where et is the expression tree that represents the property assignment.

So, if we can’t do this, let’s try the next best thing that is splitting retrieving the property information from the retrieving the value to assign o the property:

var et = Set((Person p) => p.Name, () => "me");

And this is something that the compiler can handle.

The implementation of Set receives an expression to retrieve the property information from and another expression the retrieve the value to assign to the property:

public static Expression<Action<TEntity>> Set<TEntity, TValue>(
    Expression<Func<TEntity, TValue>> propertyGetExpression,
    Expression<Func<TValue>> valueExpression)

The implementation of this method gets the property information form the body of the property get expression (propertyGetExpression) and the value expression (valueExpression) to build an assign expression and builds a lambda expression using the same parameter of the property get expression as its parameter:

public static Expression<Action<TEntity>> Set<TEntity, TValue>(
    Expression<Func<TEntity, TValue>> propertyGetExpression,
    Expression<Func<TValue>> valueExpression)
{
    var entityParameterExpression = (ParameterExpression)(((MemberExpression)(propertyGetExpression.Body)).Expression);

    return Expression.Lambda<Action<TEntity>>(
        Expression.Assign(propertyGetExpression.Body, valueExpression.Body),
        entityParameterExpression);
}

And now we can use the expression to translate to another context or just compile and use it:

var et = Set((Person p) => p.Name, () => name);
Console.WriteLine(person.Name); // Prints: p => (p.Name = “me”)

var d = et.Compile();

d(person);
Console.WriteLine(person.Name); // Prints: me

It can even support closures:

var et = Set((Person p) => p.Name, () => name);
Console.WriteLine(person.Name); // Prints: p => (p.Name = value(<>c__DisplayClass0).name)

var d = et.Compile();

name = "me";
d(person);
Console.WriteLine(person.Name); // Prints: me

name = "you";
d(person);
Console.WriteLine(person.Name); // Prints: you

Not so useful in the intended scenario (but still possible) is building an expression tree that receives the value to assign to the property as a parameter:

public static Expression<Action<TEntity, TValue>> Set<TEntity, TValue>(Expression<Func<TEntity, TValue>> propertyGetExpression)
{
    var entityParameterExpression = (ParameterExpression)(((MemberExpression)(propertyGetExpression.Body)).Expression);
    var valueParameterExpression = Expression.Parameter(typeof(TValue));

    return Expression.Lambda<Action<TEntity, TValue>>(
        Expression.Assign(propertyGetExpression.Body, valueParameterExpression),
        entityParameterExpression,
        valueParameterExpression);
}

This new expression can be used like this:

var et = Set((Person p) => p.Name);
Console.WriteLine(person.Name); // Prints: (p, Param_0) => (p.Name = Param_0)

var d = et.Compile();

d(person, "me");
Console.WriteLine(person.Name); // Prints: me

d(person, "you");
Console.WriteLine(person.Name); // Prints: you

The only caveat is that we need to be able to write code to read the property in order to write to it.

LINQ: Implementing The SkipLastWhile Operator

LINQ Com C#

Following my last posts (>)(>), in this post I’ll introduce the implementation of the SkipLastWhile operator.

The SkipLastWhile returns all but the last contiguous elements from a a sequence that satisfy the specified criteria and is implemented as the SkipLastWhile extension methods:

public static IEnumerable<TSource> SkipLastWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
public static IEnumerable<TSource> SkipLastWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)

The implementation of these methods is very simple. We start with an empty buffer and buffer every item that satisfies the criteria implemented by a predicate. Whenever an item doesn’t satisfy the criteria, all buffered items are yield, the buffer is cleared and the the item that doesn’t satisfy the criteria is yield:

var buffer = new List<TSource>();

foreach (var item in source)
{
    if (predicate(item))
    {
        buffer.Add(item);
    }
    else
    {
        if (buffer.Count > 0)
        {
            foreach (var bufferedItem in buffer)
            {
                yield return bufferedItem;
            }

            buffer.Clear();
        }

        yield return item;
    }
}

The overload that takes in account the index of the item only differs in the call the predicate that implements the criteria:

var buffer = new List<TSource>();
var idx = 0;

foreach (var item in source)
{
    if (predicate(item, idx++))
    {
        buffer.Add(item);
    }
    else
    {
        if (buffer.Count > 0)
        {
            foreach (var bufferedItem in buffer)
            {
                yield return bufferedItem;
            }

            buffer.Clear();
        }

        yield return item;
    }
}

You can find the complete implementation of this operator (and more) CodePlex project for LINQ utilities and operators: PauloMorgado.Linq

LINQ: Implementing The SkipLast Operator

LINQ With C# (Portuguese)

Following my last post, in this post I’ll introduce the implementation of the SkipLast operator.

The SkipLast operator returns all but a specified number of contiguous elements from the end of a sequence and is implemented as the SkipLast extension method:

public static IEnumerable<TSource> SkipLast<TSource>(this IEnumerable<TSource> source, int count)

To implement this operator, first we start by buffering, at most, a count number of items from the source sequence in an array that acts as a circular buffer:

var sourceEnumerator = source.GetEnumerator();
var buffer = new TSource[count];
int idx;

for (idx = 0; (idx < count) && sourceEnumerator.MoveNext(); idx++)
{
    buffer[idx] = sourceEnumerator.Current;
}

Next, we iterate over the rest of the items of the source sequence circularly buffering them and yielding the previously buffered item at the same postition:

idx = 0;

while (sourceEnumerator.MoveNext())
{
    var item = buffer[idx];

    buffer[idx] = sourceEnumerator.Current;

    idx = (idx + 1) % count;

    yield return item;
}

If the number of items to skip is greater or equal to the number of items in the source sequence, sourceEnumerator.MoveNext() will return false on the first iteration of the while loop and an empty sequence will be produced.

As with the TakeLast operator, a few optimizations can be made here.

The first is obvious, if the requested number of items is 0 (zero) or lower, we just return an equivalent sequence:

if (count <= 0)
{
    return source.Select(i => i);
}

The second is if the source sequence is known to implement the IList<T> interface. Objects implementing this interface have a Count property and indexed access to its items which allows us to optimize the production of the final sequence.

If the number of items to skip is equal to or greater than the number of items in the source sequence, we just return an empty sequence:

var list = source as IList<TSource>;

if (list != null)
{
    if (count >= list.Count)
    {
        return System.Linq.Enumerable.Empty<TSource>();
    }

    // ...
}

If the number of items in the source sequence is greater than the number of items to skip, producing the final sequence consists of yielding all the items in the source sequence except the last count items:

int returnCount = list.Count - count;

for (int idx = 0; idx < returnCount; idx++)
{
    yield return list[idx];
}

You can find the complete implementation of this operator (and more) CodePlex project for LINQ utilities and operators: PauloMorgado.Linq

LINQ: Introducing The Skip Last Operators

LINQ With C# (Portuguese)

After having introduced the TakeLast operators (>)(>)(>), it makes sense to introduce their duals: the SkipLast operators.

Name Description Example
SkipLast<TSource>(IEnumerable<TSource>)

Returns all but a specified number of contiguous elements from the end of a sequence.

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

var lowerGrades = grades
                  .OrderBy(g => g)
                  .SkipLast(3);

Console.WriteLine("All grades except the top three are:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

/*
This code produces the following output:

All grades except the top three are:
56
59
70
82
*/
SkipLastWhile<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)

Returns all the elements from sequence skipping those at the end as long as the specified condition is true.

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

var lowerGrades = grades
                 .OrderBy(grade => grade)
                 .SkipLastWhile(grade => grade >= 80);

Console.WriteLine("All grades below 80:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

/*
This code produces the following output:

All grades below 80:
56
59
70
*/
SkipLastWhile<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>)

Returns all the elements from sequence skipping those at the end as long as the specified condition is true.

int[] amounts =
    {
        5000,
        2500,
        5500,
        8000,
        6500,
        4000,
        1500,
        9000
    };

var query = amounts
            .SkipLastWhile((amount, index) => amount > index * 1000);

foreach (int amount in query)
{
    Console.WriteLine(amount);
}

/*
 This code produces the following output:

9000
*/

You can find these (and more) operators in my CodePlex project for LINQ utilities and operators: PauloMorgado.Linq

LINQ: Implementing The TakeLastWhile Operator

LINQ With C# (Portuguese)

Following my last posts (>)(>), in this post I’ll introduce the implementation of the TakeLastWhile operator.

The TakeLastWhile operator returns last contiguous elements from a sequence that satisfy the specified criteria and is implemented as the TakeLastWhile extension methods:

public static IEnumerable<TSource> TakeLastWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
public static IEnumerable<TSource> TakeLastWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)

The implementation of the first method is very simple. We start with an empty buffer and buffer every item that satisfies the criteria implemented by a predicate. Whenever an item doesn’t satisfy the criteria, the buffer is cleared:

var buffer = new List<TSource>();

foreach (var item in source)
{
    if (predicate(item))
    {
        buffer.Add(item);
    }
    else
    {
        buffer.Clear();
    }
}

After traversing the source sequence, we just yield all the items, if any, in the buffer:

foreach (var item in buffer)
{
    yield return item;
}

The overload that takes in account the index of the item only differs in the call the predicate that implements the criteria:

var buffer = new List<TSource>();
var idx = 0;

foreach (var item in source)
{
    if (predicate(item, idx++))
    {
        buffer.Add(item);
    }
    else
    {
        buffer.Clear();
    }
}

foreach (var item in buffer)
{
    yield return item;
}

You can find the complete implementation of this operator (and more) CodePlex project for LINQ utilities and operators: PauloMorgado.Linq

LINQ: Implementing The TakeLast Operator

LINQ With C# (Portuguese)

Following my last post, in this post I’ll introduce the implementation of the TakeLast operator.

The TakeLast operator returns a specified number of contiguous elements from the end of a sequence and is implemented as the TakeLast extension method:

public static IEnumerable<TSource> TakeLast<TSource>(this IEnumerable<TSource> source, int count)

To implement this operator, first we start by buffering, at most, a count number of items from the source sequence in an array that acts as a circular buffer:

var sourceEnumerator = source.GetEnumerator();
var buffer = new TSource[count];
var numOfItems = 0;
int idx;

for (idx = 0; (idx < count) && sourceEnumerator.MoveNext(); idx++, numOfItems++)
{
    buffer[idx] = sourceEnumerator.Current;
}

If the number of buffered items (numOfItems) is less than the requested number of items (count), we just yield all the buffered items:

if (numOfItems < count)
{
    for (idx = 0; idx < numOfItems; idx++)
    {
        yield return buffer[idx];
    }

    yield break;
}

Next, we iterate over the rest of the items circularly buffering them:

for (idx = 0; sourceEnumerator.MoveNext(); idx = (idx + 1) % count)
{
    buffer[idx] = sourceEnumerator.Current;
}

And finally, we just iterate over the buffered items and yield them:

for (; numOfItems > 0; idx = (idx + 1) % count, numOfItems--)
{
    yield return buffer[idx];
}

There are two optimizations you can make here.

The first is obvious, if the requested number of items is 0 (zero), we just return an empty sequence:

if (count <= 0)
{
    return System.Linq.Enumerable.Empty<TSource>();
}

The second is if the source sequence is known to implement the IList<T> interface. Objects implementing this interface have a Count property and indexed access to its items which allows us to optimize the production of the final sequence.

Producing the final sequence consists of yielding the required number of items from the end of the list (or all of them if the list contains less items than required):

int listCount = list.Count;

for (int idx = listCount - ((count < listCount) ? count : listCount); idx < listCount; idx++)
{
    yield return list[idx];
}

You can find the complete implementation of this operator (and more) CodePlex project for LINQ utilities and operators: PauloMorgado.Linq