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.
-
-
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.
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 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:
-
Metro Internet Explorer is always a 64bit application on 64bit Windows 8.
-
Javascript Metro Style Applications don’t announce if they are 32bit or 64bit.
-
They look like they are running on a 32bit Windows 8.
-
Desktop Internet Explorer retains the same behavior introduced with Internet Explorer 8.
-
Metro Style C#/VB Applications hosting the web browser (
WebView control) exhibit the same behavior as
Internet Explorer.
-
Desktop WPF Applications hosting the web browser (
WebBrowser control) retain the same behavior introduced with
Internet Explorer 8.
-
BUILD, the conference that everybody is expecting Microsoft to present the first news about Windows 8, for Developers, is about to begin. The good news is that the Keynotes will be available live online on the site www.buildwindows.com!
Channel9 is also doing extensive cover of the event with online sessions, interviews, discussion panels, etc. (more news here: http://news.cnet.com/8301-10805_3-20103036-75/behind-the-scenes-at-microsofts-channel-9/).
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:
(?<=<\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.
Microsoft has launched the MSDN Forum Assistant, which allows you to access MSDN Forums and receive updates directly to your desktop. Features include Ask a Question, Latest Post, Thread Updates, Priority Support, and Forum Q&A. You can download the MSDN Forum Assistant here: http://gallery.live.com/liveItemDetail.aspx?li=822a3787-89e8-4c6d-8fc4-a413437d86e9
You can find more information here:
A Visual Studio UserVoice site has been set up to collect community feedback:
For filing bugs, the Visual Studio Connect site is still the place to go:
In order to complete the registration as a Windows Phone developer an application needs to be submitted.
Following the advise of Caio, I wrote a GUID Generator. It has now been published and you can get it here.
Have you ever felt the need for a freshly generated GUID?
With this application you can have a freshly generated GUID whenever you want.
A GUID (Globally Unique Identifier) is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated. Do you want o try?
Talking with friends with iPhone and Android phones I became aware that there is no such application for those platforms. How can they live without one?
I make extensive use of extension methods, either to make classes small and focused or to improve readability.
While porting a .NET 1.1 WinForms application to C# 3.0, I found lots of code like this:
delegate int Int32DelegateStringBoolean(string text, bool flag);
void DoStuff()
{
// ...
var x = (int)this.Invoke(new Int32DelegateStringBoolean(GetStuff), new object[] { "some text", true });
// ...
}
int GetStuff(string text, bool flag)
{
// ...
}
.NET 2.0 introduced a nicer API and it became possible to write the code calling Invoke like this:
var x = (int)this.Invoke(new Int32DelegateStringBoolean(GetStuff), "some text", true);
But it’s still not strongly typed enough to my taste and the compiler can’t verify if any mistake was made. This will still be valid code at compile time that will break at run time:
var x = (long)this.Invoke(new Int32DelegateStringBoolean(GetStuff), "some text", 10M, 5);
To make the code safer and more readable, I decided to create extension methods to extend the Control class and provide strongly type Invoke methods.
Instead of defining custom delegates for each need, I used the Action and Func delegates exiting in the framework and wrote extension methods like this:
public static TResult InvokeFunc<T1, T2, TResult>(this Control control, Func<T1, T2, TResult> func, T1 param1, T2 param2)
{
return (TResult)(control.Invoke(func, param1, param2));
}
Now I can replace the call to Invoke with this call:
var x = this.InvokeFunc<string, bool, int>(new Func<string, bool, int>(GetStuff), "some text", true);
And the compiler is now able to match the type of the delegate, the parameters and the return value.
Starting with the C# 2.0 compiler, there is no need to write the delegate instantiation if the compiler can infer the type of the delegate, which makes the code even simpler:
var x = this.InvokeFunc<string, bool, int>(GetStuff, "some text", true);
The C# compiler is even capable of inferring the type parameters of the InvokeFunc method making the code even smaller and more readable:
var x = this.InvokeFunc(GetStuff, "some text", true);
A lot better than what we started with, isn’t it?
So far, I’ve implemented these:
/// <summary>
/// Provides extended functionality to <see cref="System.Windows.Forms.Control"/>.
/// </summary>
public static class ControlExtensions
{
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to invoke the function on.</param>
/// <param name="func">The function to invoke.</param>
/// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
public static TResult InvokeFunc<TResult>(this Control control, Func<TResult> func)
{
return (TResult)(control.Invoke(func));
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to invoke the function on.</param>
/// <param name="func">The function to invoke.</param>
/// <param name="param1">The parameter of the action.</param>
/// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
public static TResult InvokeFunc<T1, TResult>(this Control control, Func<T1, TResult> func, T1 param1)
{
return (TResult)(control.Invoke(func, param1));
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to invoke the function on.</param>
/// <param name="func">The function to invoke.</param>
/// <param name="param1">The first parameter of the function.</param>
/// <param name="param2">The second parameter of the function.</param>
/// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
public static TResult InvokeFunc<T1, T2, TResult>(this Control control, Func<T1, T2, TResult> func, T1 param1, T2 param2)
{
return (TResult)(control.Invoke(func, param1, param2));
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to invoke the function on.</param>
/// <param name="func">The function to invoke.</param>
/// <param name="param1">The first parameter of the function.</param>
/// <param name="param2">The second parameter of the function.</param>
/// <param name="param3">The third parameter of the function.</param>
/// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
public static TResult InvokeFunc<T1, T2, T3, TResult>(this Control control, Func<T1, T2, T3, TResult> func, T1 param1, T2 param2, T3 param3)
{
return (TResult)(control.Invoke(func, param1, param2, param3));
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
/// <typeparam name="T4">The type of the forth parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to invoke the function on.</param>
/// <param name="func">The function to invoke.</param>
/// <param name="param1">The first parameter of the function.</param>
/// <param name="param2">The second parameter of the function.</param>
/// <param name="param3">The third parameter of the function.</param>
/// <param name="param4">The forth parameter of the function.</param>
/// <returns>A <typeparamref name="TResult"/> that contains the return value from the function (<paramref name="func"/>) being invoked.</returns>
public static TResult InvokeFunc<T1, T2, T3, T4, TResult>(this Control control, Func<T1, T2, T3, T4, TResult> func, T1 param1, T2 param2, T3 param3, T4 param4)
{
return (TResult)(control.Invoke(func, param1, param2, param3, param4));
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <param name="control">The control to invoke the action on.</param>
/// <param name="action">The action to invoke.</param>
public static void InvokeAction(this Control control, Action action)
{
control.Invoke(action);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <param name="control">The control to invoke the action on.</param>
/// <param name="action">The action to invoke.</param>
/// <param name="param">The parameter of the action.</param>
public static void InvokeAction<T>(this Control control, Action<T> action, T param)
{
control.Invoke(action, param);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
/// <param name="control">The control to invoke the action on.</param>
/// <param name="action">The action to invoke.</param>
/// <param name="param1">The first parameter of the action.</param>
/// <param name="param2">The second parameter of the action.</param>
public static void InvokeAction<T1, T2>(this Control control, Action<T1, T2> action, T1 param1, T2 param2)
{
control.Invoke(action, param1, param2);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
/// <param name="control">The control to invoke the action on.</param>
/// <param name="action">The action to invoke.</param>
/// <param name="param1">The first parameter of the action.</param>
/// <param name="param2">The second parameter of the action.</param>
/// <param name="param3">The third parameter of the action.</param>
public static void InvokeAction<T1, T2, T3>(this Control control, Action<T1, T2, T3> action, T1 param1, T2 param2, T3 param3)
{
control.Invoke(action, param1, param2, param3);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
/// <typeparam name="T4">The type of the forth parameter of the action.</typeparam>
/// <param name="control">The control to invoke the action on.</param>
/// <param name="action">The action to invoke.</param>
/// <param name="param1">The first parameter of the action.</param>
/// <param name="param2">The second parameter of the action.</param>
/// <param name="param3">The third parameter of the action.</param>
/// <param name="param4">The forth parameter of the action.</param>
public static void InvokeAction<T1, T2, T3, T4>(this Control control, Action<T1, T2, T3, T4> action, T1 param1, T2 param2, T3 param3, T4 param4)
{
control.Invoke(action, param1, param2, param3, param4);
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to BeginInvoke the function on.</param>
/// <param name="func">The function to BeginInvoke.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeFunc<TResult>(this Control control, Func<TResult> func)
{
return control.BeginInvoke(func);
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to BeginInvoke the function on.</param>
/// <param name="func">The function to BeginInvoke.</param>
/// <param name="param1">The parameter of the action.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeFunc<T1, TResult>(this Control control, Func<T1, TResult> func, T1 param1)
{
return control.BeginInvoke(func, param1);
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to BeginInvoke the function on.</param>
/// <param name="func">The function to BeginInvoke.</param>
/// <param name="param1">The first parameter of the function.</param>
/// <param name="param2">The second parameter of the function.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeFunc<T1, T2, TResult>(this Control control, Func<T1, T2, TResult> func, T1 param1, T2 param2)
{
return control.BeginInvoke(func, param1, param2);
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to BeginInvoke the function on.</param>
/// <param name="func">The function to BeginInvoke.</param>
/// <param name="param1">The first parameter of the function.</param>
/// <param name="param2">The second parameter of the function.</param>
/// <param name="param3">The third parameter of the function.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeFunc<T1, T2, T3, TResult>(this Control control, Func<T1, T2, T3, TResult> func, T1 param1, T2 param2, T3 param3)
{
return control.BeginInvoke(func, param1, param2, param3);
}
/// <summary>
/// Executes the specified function (<paramref name="func"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the function.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the function.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the function.</typeparam>
/// <typeparam name="T4">The type of the forth parameter of the function.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="control">The control to BeginInvoke the function on.</param>
/// <param name="func">The function to BeginInvoke.</param>
/// <param name="param1">The first parameter of the function.</param>
/// <param name="param2">The second parameter of the function.</param>
/// <param name="param3">The third parameter of the function.</param>
/// <param name="param4">The forth parameter of the function.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeFunc<T1, T2, T3, T4, TResult>(this Control control, Func<T1, T2, T3, T4, TResult> func, T1 param1, T2 param2, T3 param3, T4 param4)
{
return control.BeginInvoke(func, param1, param2, param3, param4);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <param name="control">The control to BeginInvoke the action on.</param>
/// <param name="action">The action to BeginInvoke.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeAction(this Control control, Action action)
{
return control.BeginInvoke(action);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T">The type of the parameter.</typeparam>
/// <param name="control">The control to BeginInvoke the action on.</param>
/// <param name="action">The action to BeginInvoke.</param>
/// <param name="param">The parameter of the action.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeAction<T>(this Control control, Action<T> action, T param)
{
return control.BeginInvoke(action, param);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
/// <param name="control">The control to BeginInvoke the action on.</param>
/// <param name="action">The action to BeginInvoke.</param>
/// <param name="param1">The first parameter of the action.</param>
/// <param name="param2">The second parameter of the action.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeAction<T1, T2>(this Control control, Action<T1, T2> action, T1 param1, T2 param2)
{
return control.BeginInvoke(action, param1, param2);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
/// <param name="control">The control to BeginInvoke the action on.</param>
/// <param name="action">The action to BeginInvoke.</param>
/// <param name="param1">The first parameter of the action.</param>
/// <param name="param2">The second parameter of the action.</param>
/// <param name="param3">The third parameter of the action.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeAction<T1, T2, T3>(this Control control, Action<T1, T2, T3> action, T1 param1, T2 param2, T3 param3)
{
return control.BeginInvoke(action, param1, param2, param3);
}
/// <summary>
/// Executes the specified action (<paramref name="action"/>) on the thread that owns the control's underlying window handle.
/// </summary>
/// <typeparam name="T1">The type of the first parameter of the action.</typeparam>
/// <typeparam name="T2">The type of the second parameter of the action.</typeparam>
/// <typeparam name="T3">The type of the third parameter of the action.</typeparam>
/// <typeparam name="T4">The type of the forth parameter of the action.</typeparam>
/// <param name="control">The control to BeginInvoke the action on.</param>
/// <param name="action">The action to BeginInvoke.</param>
/// <param name="param1">The first parameter of the action.</param>
/// <param name="param2">The second parameter of the action.</param>
/// <param name="param3">The third parameter of the action.</param>
/// <param name="param4">The forth parameter of the action.</param>
/// <returns>An System.IAsyncResult that represents the result of the operation.</returns>
public static IAsyncResult BeginInvokeAction<T1, T2, T3, T4>(this Control control, Action<T1, T2, T3, T4> action, T1 param1, T2 param2, T3 param3, T4 param4)
{
return control.BeginInvoke(action, param1, param2, param3, param4);
}
}
Use them if you need to.

Red Gate gave me a few licenses of .NET Reflector to give away.
The first to answer to this post in any of my blogs with a phrase about .NET Reflector and name and contact e-mail will get a free license.
Hurry up! There aren’t many!
Update: I've given all licenses. Sorry for those who didn't get one.

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.
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.
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.
Reading John D. Cook’s blog post about how much does typing speed matter in software development, the way John compares software development to writing a book and not typing the book text or composing music and not playing music, made me think about the usual comparisons made between software development and other activities.
Like John, I see software development as a creative activity comparable to writing a book (or any other text) or composing music.
Typing the book text or playing an already composed music might, at most, be compared to programming in its most basic form which is introducing a pre-written (or pre-developed program) into the computer (or system).
And that brings me to assembling cars. The function of a car assembly line is to assemble a pre-developed car using a pre-developed set of steps. It’s comparable to typing or playing music not composing the text or music.
That doesn’t mean that people working on a car assembly line are dumb and incapable of being critical or creative. They are just not supposed to act on their own at the assembly line. They have a strict plan to follow. Any input they have to the assembly process must fed the development of the car or its assembly process.
When I hear Lean software development dream sellers comparing software development to assembling cars, I can only think that:
-
They don’t know the first thing about car development and assembly
-
They don’t know the first thing about software development
-
All of the above
It’s not that I don’t think Lean principals can be used in the IT industry, or even software development in particular. It’s this silver bullet that solves all the problems of the universe that people that haven’t the faintest idea what I do want to force down my throat that bothers me.
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

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

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

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

Some time ago I needed to retrieve the last items of a sequence that satisfied some criteria and, looking at the operators available in the Enumerable class, I noticed that there wasn’t such operator.
The only way to achieve this was to reverse the sequence, take the items that satisfied the criteria and reverse the resulting sequence. Something like this:
sequence.Reverse().TakeWhile(criteria).Reverse();
Looks quite simple, right? First we call the Reverse method to produce a new sequence with the same items as the original sequence but in the reverse order, then we call the TakeWhile method to take the first items that satisfy the criteria and then call the Reverse method again to restore the original order of the items.
The problem with this approach is that the Reverse method buffers the entire sequence before iterating through its items in the reverse order - and the above code uses it twice. This means iterating over all items in the original sequence and buffer them all, iterating over first items of the resulting sequence that satisfy the criteria and buffer them all and, finally, iterate over that result to produce the final sequence.
If you’re counting, you’ve come to the conclusion that all items in the original sequence will be iterated over once and the ones in the resulting sequence will be iterated again three times. If the original sequence is large, this can take lots of memory and time.
There’s another issue if you’re using the variant the uses the index of the item in the original sequence in the evaluation of the selection criteria (>). When we reverse the order of the items, the indexes will be reversed and the predicate must take that in account, which might not be possible if you don’t know the number of items in the original sequence.
There must be a better way, and that’s why I implemented the Take Last Operators:
| Name |
Description |
Example |
| TakeLast<TSource>(IEnumerable<TSource>) |
Returns a specified number of contiguous elements from the end of a sequence.
|
int[] grades = { 59, 82, 70, 56, 92, 98, 85 };
var topThreeGrades = grades
.OrderBy(grade => grade)
.TakeLast(3);
Console.WriteLine("The top three grades are:");
foreach (int grade in topThreeGrades)
{
Console.WriteLine(grade);
}
/*
This code produces the following output:
The top three grades are:
98
92
85
*/
|
| TakeLastWhile<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) |
Returns the elements from the end of a sequence as long as the specified condition is true.
|
string[] fruits =
{
"apple",
"passionfruit",
"banana",
"mango",
"orange",
"blueberry",
"grape",
"strawberry"
};
var query = fruits
.TakeLastWhile(fruit => string.Compare("orange", fruit, true) != 0);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
blueberry
grape
strawberry
*/
|
| TakeLastWhile<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>) |
Returns the elements from the end of a sequence as long as the specified condition is true.
|
string[] fruits =
{
"apple",
"passionfruit",
"banana",
"mango",
"orange",
"blueberry",
"grape",
"strawberry"
};
var query = fruits
.TakeLastWhile((fruit, index) => fruit.Length >= index);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
strawberry
*/
|
You can find these (and more) operators in my CodePlex project for LINQ utilities and operators: PauloMorgado.Linq
More Posts
« Previous page -
Next page »