38 posts categorized "Language"

04/07/2014

New Love for .NET and C#

At the Build 2014 conference, Microsoft showed new love for .NET. This blog post shows how Microsoft's love reveals.

WP_20140403_07_28_04_Pro

.NET Compiler Platform

The biggest thing for .NET is the .NET Compiler Platform ("Roslyn"). In development since the year 2009, Roslyn is nearing completion and has a new preview available.

Both C# and Visual Basic compilers are rebuilt using this compiler platform. What is the advantage of rebuilding the compiler when there are already working ones that have been implemented with native code?

For the Microsoft teams, this platform gives a clean architecture to evolve on. It's a lot easier to add features to C# and Visual Basic. Implementing a new features for these two languages doesn't mean the effort duplicated for every language, it can be done with just 1.2x instead of 2x. The effort to implementing new language features is a lot less compared to the older native C# compiler, as can be seen in the number of new features for C#.

For partners, it is a lot easier to create source-based tools and extensions for Visual Studio. Xamarin will use the .NET Compiler Platform in an upcoming edition. I also bet, tools like ReSharper will make use of this platform to create new features.

For developers, the .NET Compiler Platform gives a richer C# IDE experience. Coming with the preview you can already see smarter refactoring features. More to come :-)

Anders Hejlsberg demonstrated just three small changes in the code base for defining a new string literal. As the .NET Compiler Platform is open source, changes could be done by everyone. I just don't expect many to do their own C#. However using the .NET Compiler Platform it is easy to define guidelines for code styling, and easy allow for automatic code changes with preview of the changes shown.

Dustin Campbell demonstrated how easy it is to use the .NET Compiler Platform SDK to create a guideline for requiring braces with the block of if and else statements.

The preview can be downloaded from Microsoft Connect after registration.

.NET Foundation

The .NET Foundation was announced for faster open development and collaboration around many open source technologies for .NET. Among the projects in the foundation are the .NET Compiler Platform, ASP.NET MVC, ASP.NET Web API, Composition (MEF), ASP.NET SignarlR, Entity Framework, Rx (Reactive Extensions), Windows Azure .NET SDK, and also third party libraries such as Xamarin.Mobile, Xamarin.Auth, Couchbase for .NET, .NET Map Reduce API for Hadoop...

C# 6

Let's get into the history of C#. C# 2.0 offered generics with the language. C# 3 added LINQ and all the language features needed for LINQ such as Lambda expressions, type inference, anonymous types, and others. The theme of C# 4 was dynamic to make an easier integration with scripting languages and COM, offering the dynamic keyword, optional and named parameters. C# 5 was about async programming, just offering two new language keywords async and await. However, these small keywords again changed programming dramatically.

C# 6 is not about such a big change like generics, LINQ, or dynamic. However, it has many changes. With the .NET Compiler Platform, it is a lot easier to create new features. Thus many things that needed to wait with previous editions can be done now. Among the things that were shown at Build are primary constructors, declaration expressions, and indexed members.

Creating immutable types was always possible with .NET, but we had to write a lot of code. With the new language features, creating such types is possible reducing the code a lot.

New JIT Compiler, .NET Native

RyuJIT is a new JIT compiler for the .NET runtime. This compiler is a lot faster than the one now part of .NET. Rujit CTP 3 is available now. This version supports SIMD instructions (running the same operation on multiple data points simultaneously.

It gets even faster with .NET Native. 60% faster startup for Windows Store apps, and much smaller memory footprint. This product consists from a .NET Native compiler that makes use of a VC++ compiler backend and the .NET Native runtime (refactored and optimized CLR).

With Windows Store apps, it is still possible to upload MSIL app packages to the store. Later on the compiler in the cloud compiles the app in the store that is compiled for ARM and x64 architectures. x86 will follow.

Using this compiler also has the advantage that the compiler creates just one file containing native code for all libraries. Using IL code tools to analyze this code is no longer possible, it's native code.

Not only this, this compiler also creates just one file containing native code for all the libraries. Currently this native compiler is only available for Windows Store apps, but other technologies will follow.

Apps such as Wordament and Fresh Paint already make use of .NET Native and see great improvements.

Summary

With these developments I'm seeing really big steps forward with .NET. With many of these technologies it's just the beginning. For example, I can imagine big improvements in upcoming tools based on the .NET Compiler Platform. And then don't forget the new C# language features, .NET Native, RyuJIT, and the huge open source progress going on.

Another big thing for .NET are Universal Apps that I talk about in another blog post.

Christian

CN innovation

 

09/16/2011

C# Future Directions

Thursday at Windows Build Anders Hejlsberg presented the future directions of C#. The new version number of C# is 5. The major features on this version are the integration of the Windows Runtime (WinRT) and of course the already well known async and await keywords for asynchronous programming. Anders also talked about some other cool features that I’ll introduce here.

Async Programming

The preview of the async features for C# v5 are out for some time now. I’ve already shown these keywords in a blog article from last year. Deeper information on this will follow in upcoming blog articles. Anders also talked about some other cool features that I’ll introduce here.

Great news at the conference is that the WinRT API offers async versions of the API if the function needs more than 15ms. This are 10-15% of the methods of the API. These APIs only offer async versions. Functionality like file I/O, network I/O…

And async methods have a big place in the .NET Framework as well. This makes it a lot easier to write async applications. And all applications should use this! The user interface must be very very responsive.

WinRT API asynchronous methods use IAsyncOperation<T>, .NET methods Task<T>, and JavaScript promises.

Windows Runtime

The Windows Runtime is written natively. It’s a new version of COM. Using namespaces, classes, constructors, statics, events… Using it from  C# feels very natural. Although it’s implemented natively it nearly cannot be differentiated from C# calling into managed methods. The Windows Runtime team took a lot of features from .NET and added it to the native Windows API.

It’s similar easy to create C# types that can be used from any language making use of WinRT, e.g. JavaScript. Interop is made easy, no longer [DllImport] and COM Interop attributes. Just create a public C# type that is sealed and restricted to the types of the WinRT (or types that are mapped automatically like collection interface types). The method GetMovies() returning IAsyncOperation<IList<Movie>> can be called directly from JavaScript. For Task<T> can be easily converted to IAsyncOperation<T>.

Caller Info Attributes

C++ allows changing the code line numbers and filenames with __LINE__ and __FILE__ macros. Macros are not possible in C# and never will be. However, this feature now made it into C# by using optional parameters. The attributes CallerFilePath, CallerLineNumber, and CallerMembername can be used with optional parameters. Thus it’s easy to change the line numbers like in C++ but without Macros.

Compiler as a Service – Codename Roslyn

Looking more into the future of C#, Anders introduced the current state of compiler as a service. Scenarios that are possible with this are meta-programming, read-eval-print loops, DSL embedding, accessing the complete language object model…

Anders showed how to copy C# code and paste it as Visual Basic, and the other way around. Refactoring a data class by implementing INotifyPropertyChanged to extend the properties automatically. A C# interactive Window where code can be added on the fly including intellisense and refactoring features.

I think this to be a big changer in the features available within Visual Studio and expect a lot of extensions not only from Microsoft but also coming from the community.

A CTP will be available In four weeks from now.

Summary

To summarize the most important parts: C# deeply supports the Windows Runtime, makes async programming really easy, hybrid C#/JavaScript applications are easy to do, and a CTP for Roslyn will be available soon.

Christian

CN innovation

06/10/2011

Filter Weekdays from a Date Range

Jalpesh p. Vadgama made an blog post for C# beginners to find Saturday, Sunday from a date range using a simple for loop and switch statements. I had a similar requirement where the implementation is more reusable that I like to share now. The code sample makes use of C# features such as extension methods, LINQ, the yield statement, and the params keyword.

Within Jalpesh’s code a for loop iterates through a date range by using the time span between the dates and a for loop to iterate until the number of dates is reached. Using the DayOfWeek property of the DateTime type the weekday was accessed, and with a switch statement.

Here is the new version. I’m creating an extension method to the DateTime type, so the method WeekdaysFromDateRange can be used directly with the DateTime type. fromDate and toDate are the first parameters on the method. The last parameter is an DayOfWeek array that with the params keyword allows passing any number of DayOfWeek values. Within the implementation of the method a while loop iterates through all dates up to the end date and checks by using the Contains extension method defined in the System.Linq namespace if the weekday is one of the required ones and if it is returns it with the yield return statement.

 

1 public static class DateTimeExtension 2 { 3 public static IEnumerable<DateTime> WeekdaysFromDateRange( 4 this DateTime fromDate, DateTime toDate, params DayOfWeek[] dayOfWeek) 5 { 6 DateTime date = fromDate; 7 while (date <= toDate) 8 { 9 if (dayOfWeek.Contains(date.DayOfWeek)) 10 yield return date; 11 date = date.AddDays(1); 12 } 13 } 14 }

This new method can now be used like a method from the DateTime types, passing an end date and any number of weekdays. In the sample code I’m passing DayOfWeek.Saturday and DayOfWeek.Sunday so that all Saturdays and Sundays are displayed within the foreach loop.

.
1 DateTime beginDate = new DateTime(2011, 3, 1); 2 DateTime endDate = new DateTime(2011, 6, 4); 3 foreach (var date in beginDate.WeekdaysFromDateRange( 4 endDate, DayOfWeek.Saturday, DayOfWeek.Sunday)) 5 { 6 Console.WriteLine("{0:D}", date); 7 }
Running the application the resulting dates are shown with the long date format.
image
More information on C# language features in my book Professional C# 4 and .NET 4 and in my C# Workshops.
Christian
CN innovation

11/19/2010

Async Programming with .NET and C# v.next

As more and more cores are the norm with PC’s (I also expect to have smartphones with multi-core CPUs soon), programming with multiple threads gets more and more important.

This blog post gives an introduction to a new C# feature for working asynchronously by comparing it to older technologies.

.NET has some history on async programming:

  • With .NET 1.0 the async pattern was available to have a standard way to deal with long running methods.
  • .NET 2.0 added the async component pattern or async event pattern that made it easier with Windows-based programs. The async pattern from .NET 1.0 had the disadvantage that a callback method that is invoked when the long running operation completes makes use of a background thread and thus it is necessary to switch to the UI thread that owns the synchronization context.
  • With .NET 4 several enhancements have been done to write asynchronous methods. .NET 4 added a standard cancellation mechanism, the Task library and Parallel Lf deINQ.

C# so far only had the lock keyword to synchronize multiple threads. This changes with the next version of C# that offers async and await keywords.

Before showing the upcoming C# feature let’s compare this with older ways of programming asynchronously. The first sample shows downloading some data in a synchronous manner with the WebClient class. DownloadData can be used to get data from a server into an byte array.

private void OnSync(object sender, RoutedEventArgs e) { byte[] data = null; textStatus.Text = string.Empty; using (WebClient client = new WebClient()) { data = client.DownloadData(address); textStatus.Text = "Completed"; } }

Doing this from within a Windows application, the user interface is stalled while the synchronous method DownloadData waits until all the data is retrieved from the server.

To not block the UI, the data can be retrieved in an async manner. The second sample shows the use of the async pattern. This pattern defines a Begin and End prefix to the methods used for async calls and makes use of the IAsyncResult interface.

Contrary to the HttpWebRequest class, the WebClient class does not offer this pattern by itself. The HttpWebRequest class could be used to invoke the methods BeginGetResponse and EndGetResponse that follow the async pattern. To invoke any synchronous method in an async manner also a delegate can be used. This is shown in this sample.

For invoking the method WebClient.DownloadData a delegate that requires a string parameter and returns a byte array is defined with the Func<string, byte[]> delegtate. The delegate instance named download references a lambda expression that gets a string parameter and returns the result from the WebClient.DownloadData method. The implementation of the lambda expression is invoked asynchronously by calling the BeginInvoke method from the delegate instance. The first argument of this method defines the input data for the method that is invoked by the delegate. With this argument value the method that is referenced by the delegate is invoked from  thread pool thread.

The second parameter is of type AsyncCallback that is void and requires an IAsyncResult parameter. This parameter defines the method that is invoked as soon as the asynchronous method completes. Invoking the method EndInvoke from the delegate instance, the result (in this case a byte[]) is returned.

Invoking methods and properties from UI elements cannot be done directly, as the method that is assigned to the AsyncCallback is running within a background thread. To switch back to the UI thread, with WPF the Dispatcher property that returns a DispatcherObject can be used. The Invoke method of the DispatcherObject requires a delegate with the first parameter. Here, the Action<string> delegate is used to pass a string to the method.

private void OnAsync1(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; byte[] data = null; using (WebClient client = new WebClient()) { Func<string, byte[]> download = addr => { return client.DownloadData(addr); }; download.BeginInvoke(address, new AsyncCallback(ar => { data = download.EndInvoke(ar); Dispatcher.Invoke( new Action<string>(s => textStatus.Text = s), "Completed"); }), null); } }

Because of this complexity in special with Windows applications where it is necessary to get back to the UI thread the async event pattern was introduced with .NET 2.0. This pattern defines that a async method is postfixed with the name Async and defines an event with the postfix Completed that is invoked as soon as the async mehtod finishes. The big advantage in contrast to the callback method with the async pattern is that the event handler that is assigned to the Completed event is invoked from a thread that has the synchronization context. With WPF or Windows Forms applications this is the UI thread.

Doing the same sample as before with the async event pattern methods from the WebClient class can be used directly as this class offers an implementation of this pattern. The DownloadDataCompleted event a lambda expression is assigned to get the result from the async call, and change that status information in a TextBlock directly.

private void OnAsync2(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; using (WebClient client = new WebClient()) { client.DownloadDataCompleted += (sender1, e1) => { byte[] data = e1.Result; textStatus.Text = "completed"; }; client.DownloadDataAsync(new Uri(address)); } }

With WPF and Windows Forms the async event pattern is a lot easier to deal with contrary to the async pattern. However, it is still very different to programming synchronously. Before the async method is invoked it must be defined what happens when the method is finished which can make it quiet complex reading such code.

A goal of the new C# keywords is to write asynchronous code in a way that is similar to programming synchronous code. This sample requires the use of the Visual Studio Async CTP and a reference to the AsyncCTPLibrary assembly. This assembly contains an extension method to WebClient named DownloadDataTaskAsync that returns Task<byte[]>. Instead of using the task that is returned from this method the await keyword is used that means we’re waiting on the result of the task that is of type byte[]. Waiting here with the await keyword does not block the thread. Instead, the UI thread can do some other actions and gets informed by a message when the task is completed, so it can continue with the result that is returned from DownloadTaskAsync.

private async void OnAsync3(object sender, RoutedEventArgs e) { textStatus.Text = string.Empty; using (WebClient client = new WebClient()) { byte[] data = await client.DownloadDataTaskAsync(address); textStatus.Text = "Completed"; } }

Programming asynchronously this way is very similar to programming synchronously. The order of the code is similar to synchronous programming and it still behaves asynchronously.

async and await are just language features. It was possible to do the same with the current version of the compiler, the code just reads more complex.

This is really a great feature of the next version of the C# compiler. Expect more information about this in my blog.

Christian

CN innovation

Follow me on twitter

11/02/2010

My take from PDC 2010

My previous blog posts were summaries about PDC day 1 and PDC day 2. This is now a conclusion what I take with me from PDC 2010 into the next months.

Silverlight

Currently I’m working from the UI side mostly with WPF and Silverlight on the desktop, and Silverlight for Windows Phone 7. I will continue to do so.With my new LG WP7 it gets a lot easier to write phone applications. What I’ve seen is most important to writing WP7 applications is using a WP7.

Bob Muglia just clarified the strategy on Silverlight in this blog post with this emphasize:

  1. Silverlight is very important and strategic to Microsoft.
  2. We’re working hard on the next release of Silverlight, and it will continue to be cross-browser and cross-platform, and run on Windows and Mac.
  3. Silverlight is a core application development platform for Windows, and it’s the development platform for Windows Phone.

Probably MIX 2011 April 12-14, 2011 is a good date for an upcoming Silverlight release.

Windows Azure

Some of my Silverlight projects are hosted in Windows Azure. I will continue to do so. I will also dive into the new features of Windows Azure as listed on the Windows Azure Team blog, such as Windows Azure Connect (CTP available later this year), ‘Extra Small’ Windows Azure instances, the new Windows Azure portal and diagnostic information.

HTML 5 and IE 9

I’m already using IE 9 for some time. Installed the IE9 Preview 6 as well. So far I didn’t do a lot with HTML 5 other than trying the samples. I will dive deep into this technology, together with technologies that I’m already using such as ASP.NET MVC – now version 3 with the Razor view engine.

For sure MIX 2011 April 12-14, 2011 is also a good date on more news on HTML 5 and IE9.

Languages and Frameworks

And of course I’m already testing the next version of C# with async and await keywords. Also diving into the WCF and WF enhancements. Already thinking about the next edition of Professional C# 4 with .NET 4.

Christian

CN innovation

Follow me on twitter

10/29/2010

PDC 2010 Day 1

Last year’s PDC was not about completely new things, but progress, updates to existing technologies. This continues with this year’s PDC. There’s great progress on existing technologies.

Some highlights?

Steve Ballmer’s keynote was on Internet Explorer 9 and Windows Phone 7.

Internet Explorer 9

IE9 has a big focus on standard HTML 5, HTML 5 features with hardware acceleration.

A differentiation of this browser in contrast to the competition is in the integration with Windows 7. Where WPF 4 got improvements for an integration with the Windows 7 taskbar, the same is now possible for Web sites by using IE9 features. This integration is really simple – using metatags to define the items of the jumplist, and a few lines of JavaScript to add custom functionality such as start/stop buttons to the preview.

IE 9 platform preview 6 is available at http://www.ietestdrive.com.

Windows Phone 7

Of course Windows Phone 7 had a big focus at PDC. The phone is different – I’m already using it for a week, it is really different. Metro gives a cool UI experience.

twitter and facebook applications were shown – with great UI features.

And really cool – at least for all attendees - a WP7 LG Optimus 7 was given to every attendee (with the exception of government attendees).

Visual Studio gets a profiler to analyze WP7 applications. This looked like a great way to analyze bottlenecks.

For programming, Charles Petzold’s Windows Phone 7 book is available for download.

Windows Azure

Keynote part 2, Bob Muglia’s focus was on Windows Azure. It was interesting to see that Pixar RenderMan is running on Windows Azure. This makes it possible for smaller studios to create animation by renting CPU power for a specified time. I’m seeing Azure not only important for scale up and scale down scenarios, but also to have access from everywhere, from every device.

Windows Azure gets a lot of improvements:

  • Virtual Machine Role
  • Application Virtualization – transfer application images
  • Extra small instance – of course for a lower price
  • Remote Desktop
  • Full IIS
  • Virtual Network
  • Elevated Privileges
  • Windows Server 2008 R2 Roles
  • Multiple Administrators
  • Marketplace – DataMarket (known as Dallas)

Was the Visual Studio Team Foundation Server too much admin work to consider? Now it’s in the cloud!

Windows Azure AppFabric has been updated with enhancements and new services:

  • Access Control
  • Caching
  • Service Bus
  • Composite Applications

SQLAzure with

  • Reporting
  • Data Sync

 

C# and Visual Basic next

The major focus on the next version of C# and Visual Basic is on asynchronous programming. Based on the Task<T> defined by .NET 4 the language keywords async and await have been added. These keywords make it possible to  that make it possible to write applications asynchronously in a synchronous programming style. This is really cool! I’ll blog some examples on how this can be used soon.

The Async CTP is available for download.

And More

With just two days PDC it’s not possible to have a session on every technology, which doesn’t mean there’s no progress. With PDC also some pre-recorded sessions are available, e.g. on WPF, and information on the future of WPF is here. Enhancements that can be expected with the next version:

  • Hosting of Silverlight content
  • Better AirSpace management with native HWND
  • Binding and change notification for collections from background threads
  • Better integration with UI virtualization
  • Integration of Ribbon
  • more…

Expect more of this content to be covered in my blog.

Christian

CN innovation

10/19/2010

LINQ Compound From with C# and Visual Basic

The last blog post was about LINQ grouping. Next I’m stepping into compound from. With a LINQ compound from query a list where the elements contain an inner list can be flattened.

Like the previous sample, I’m using the Racer type with the query. The properties Cars and Years can be used with a compound from.

public class Racer { public string FirstName { get; set; } public string LastName { get; set; } public int Wins { get; set; } public string Country { get; set; } public int Starts { get; set; } public int PolePositions { get; set; } public string[] Cars { get; set; } public int[] Years { get; set; } //...

This time the goal of the query is to find racers based on the car which is a collection by itself. With the list of F1 champions that is returned from Formula1.GetChampions(), every champion can be a champion with multiple cars. For example, Juan Manuel Fangio won the F1 world championship with Alfa Romeo, Maserati, Mercedes, and Ferrari.

Getting into the cars from racers can be done with a compound from. The first from is to iterate the racers, and the second one the cars from each racer.

string car = "Ferrari"; var q = from r in Formula1.GetChampions() from c in r.Cars where c == car select r;

Such a compound from is changed to invoke the SelectMany method. The where and select clauses are changed to invoke the Where and Select methods.

string car = "Ferrari"; var q = Formula1.GetChampions() .SelectMany(r => r.Cars, (r1, c1) => new {Racer = r1, Car = c1}) .Where(rc => rc.Car == car) .Select(rc => rc.Racer);

The SelectMany method has several overloads. With the LINQ Query statement after the compound from both the outer collection (the racers) and the inner collection (the cars) is accessed with following clauses. So the SelectMany overload must return racers and cars. This is possible with the overload IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource>, Func<TSource, IEnumerable<TCollection>>, Func<TSource, TCollection, TResult>).

The first parameter this IEnumerable<TSource> defines an extension method, in the sample for IEnumerable<Racer>. This is returned from Formula1.GetChampions.

The second parameter Func<TSource, IEnumerable<TCollection>> is used to flatten the inner collection. This parameter specifies a delegate where the return type is IEnumerable<TCollection>. The source is a Racer, and the return by returning the country is IEnumerable<string>. So this parameter is resolved to Func<Racer, IEnumerable<string>>. The lambda expression receives a racer with the parameter r and returns a list of cars.

The third parameter Func<TSource, TCollection, TResult> defines what should be returned from the SelectMany method. The return of the method is IEnumerable<TResult>. With the sample, this resolves to Func<Racer, string, TResult>. The first parameter is the racer and the second parameter the car. This lambda expression returns an anonymous type that contains a Racer and a Car property.

The Where method uses the Car property of the anonymous type for filtering, and the Select method uses the Racer property to return all racers where the filter applies.

Instead of iterating the query directly next I’m defining a variable of type Func<string, IEnumerable<Racer>> to assign a lambda expression that contains the query. This lambda expression that’s referenced from the delegate can be invoked by passing a car as parameter. This way it’s easy to invoke methods such as Union or Intersect.

Func<string, IEnumerable<Racer>> racerByCar = car => from r in Formula1.GetChampions() from c in r.Cars where c == car select r; foreach (var r in racerByCar("Ferrari").Intersect(racerByCar("McLaren"))) { Console.WriteLine(r); }

The Visual Basic version of the above looks like this:

Dim racerByCar = Function(car As String) Return From r In Formula1.GetChampions() From c In r.Cars Where c = car Select r End Function For Each r In racerByCar("Ferrari").Intersect(racerByCar("McLaren")) Console.WriteLine(r) Next

If you would like to know the results of all F1 champions that have won the championship both with Ferrari and McLaren: Niki Lauda.

More LINQ posts:

More about LINQ with C# in my book Professional C# 4 with .NET 4, and with the language of your choice in my LINQ programming workshop. There’s also more about LINQ in the upcoming BASTA! On Tour in Munich.

Christian

CN innovation

Follow me on twitter

10/15/2010

LINQ Grouping with C# and Visual Basic

Most of the times I’m doing my code samples with C# and XAML. Of course, some samples are in C++/CLI and F#. If a customer demands I’m also doing Visual Basic. This is when it comes to translate C# to Visual Basic.

In this blog post I’m showing LINQ queries with grouping.

First, let’s start with C#. As usual I’ve a list of Formula 1 world champions that are described by a simple Racer class.

public class Racer { public string FirstName { get; set; } public string LastName { get; set; } public int Wins { get; set; } public string Country { get; set; } public int Starts { get; set; } public int PolePositions { get; set; } //...

The collection I’m working on are all Formula 1 champions since 1950 that is returned from Formula1.GetChampions().

To group the list of racers based on the country to get the number of champions of each country. This is a simple group by statement as shown.

var q = from r in Formula1.GetChampions() group r by r.Country into g orderby g.Count() descending, g.Key select new { Country = g.Key, Count = g.Count() };

The group by clause gets translated from the compiler to the GroupBy method. GroupBy gets a key-selector as argument of type Func<T, TKey>. In the sample this is Func<Racer, string> as grouping the collection by the country which is of type string. GroupBy returns IEnumerable<IGrouping<TKey, T>> what is IEnumerable<IGrouping<string, Racer>> with the sample.

The result from the grouping is ordered based on the number of elements within a group by using the Count extension method. If the count is the same, it is ordered by the key which is the country.

The result that is returned is an anonymous type with the properties Country and Count.

As the sample is now, the Count method is invoked two times. This can be changed by creating a variable within the LINQ query using the let clause.

var q = from r in Formula1.GetChampions() group r by r.Country into g let count = g.Count() orderby count descending, g.Key select new { Country = g.Key, Count = count };

Adding the racers to the result of each country is done in the next version by adding a Racers property to the anonymous type that is returned from the query. The Racers property is filled by a LINQ query that accesses the group.

var q = from r in Formula1.GetChampions() group r by r.Country into g let count = g.Count() orderby count descending, g.Key select new { Country = g.Key, Count = count, Racers = from r1 in g select r1.FirstName + " " + r1.LastName };

To reduce the result of the query to the first five groups the extension method Take is used to just return the first five.

var q = (from r in Formula1.GetChampions() group r by r.Country into g let count = g.Count() orderby count descending, g.Key select new { Country = g.Key, Count = count, Racers = from r1 in g select r1.FirstName + " " + r1.LastName }).Take(5);

Doing the same query by using extension methods instead of the LINQ Query syntax looks as shown next. The method that follows the GroupBy method can use the IEnumerable<IGrouping<string, Racer>> type that is returned.

The let clause from the LINQ query is converted to a Select method. The let clause was used to define a variable that could be used in the following LINQ clauses. The same is true by returning an anonymous type that contains the Count property from the Select method. For using the group as well with the methods that follow the Select method, the anonymous type contains the group as well.

var q = Formula1.GetChampions() .GroupBy(r => r.Country) .Select(g => new { Count = g.Count(), Group = g }) .OrderByDescending(x => x.Count) .ThenBy(x => x.Group.Key) .Select(x => new { Country = x.Group.Key, Count = x.Count, Racers = x.Group.Select(r => r.FirstName + " " + r.LastName) }) .Take(5);

Doing the same query with Visual Basic, the query looks very similar to the C# LINQ query. What’s different is that with Visual Basic Take is also defined with the LINQ query clauses.

Dim q = From r In Formula1.GetChampions() Group By country = r.Country Into Group Let count = Group.Count() Order By count Descending, country Take 5 Select Count = count, Country = country, Racers = From r In Group Order By r.LastName Select r.FirstName + " " + r.LastName

What’s also different with Visual Basic is that it’s not necessary to define a variable with the Group By clause to add the group to it, instead Group can be used. If multiple groups are used within one query, a variable can be assigned with into:

Dim q = From r In Formula1.GetChampions() Group By country = r.Country Into g = Group Let count = g.Count() Order By count Descending, country Take 5 Select Count = count, Country = country, Racers = From r In g Order By r.LastName Select r.FirstName + " " + r.LastName

If you are curious about the result of the query, here it is:

10 UK Jenson Button Jim Clark Lewis Hamilton Mike Hawthorn Graham Hill Damon Hill James Hunt Nigel Mansell Jackie Stewart John Surtees 3 Brazil Emerson Fittipaldi Nelson Piquet Ayrton Senna 3 Finland Mika Hakkinen Kimi Räikkönen Keke Rosberg 2 Australia Jack Brabham Alan Jones 2 Austria Niki Lauda Jochen Rindt

More about LINQ with C# in my book Professional C# 4 with .NET 4, and with the language of your choice in my LINQ programming workshop. There’s also more about LINQ in the upcoming BASTA! On Tour in Munich.

Christian

CN innovation

07/22/2010

Resource Management in Interop Scenarios

In a previous blog post I’ve shown a scenario for interop between MFC/C++ and WPF. This blog post didn’t further mention the requirements to release the resources. Naveen also mentioned this in a comment. This information is added here.

With the sample code a UserControl1 and a HwndSource object are instantiated.

HWND CMFCDialogAppDlg::GetUserControl1Hwnd(HWND parent, int x, int y, int width, int height)
{
HwndSourceParameters^ sourceParams = gcnew HwndSourceParameters("MFCWPFApp");
sourceParams->PositionX = x;
sourceParams->PositionY = y;
sourceParams->Height = height;
sourceParams->Width = width;
sourceParams->ParentWindow = IntPtr(parent);
sourceParams->WindowStyle = WS_VISIBLE | WS_CHILD;
m_hwndSource = gcnew HwndSource(*sourceParams);
m_wpfUC = gcnew UserControl1();
m_hwndSource->RootVisual = m_wpfUC;
return (HWND) m_hwndSource->Handle.ToPointer();
}

Both of these types implement the IDisposable interface, and thus the Dispose method should be invoked. Using C++/CLI, the Dispose method can be invoked by using the delete operator. The compiler changes delete to an invocation of the Dispose method.

CMFCDialogAppdlg::~CMFCDialogAppdlg()
{
delete m_hwndSource;
delete m_wpfUC;
}

The gcnew operator allocates an object on the managed heap. The delete operator does not release the object from the managed heap but invokes the Dispose method if available. This is a different behavior from the new/delete operators and the native heap.

What could be changed in the sample in regard to resource consumption is the use of the HwndSourceParameters. HwndSourceParameters is a managed value type and thus can be stored on the managed heap, the native heap, or the stack. Without the gcnew operator sourceParams is on the stack:

HWND CMFCDialogAppDlg::GetUserControl1Hwnd(HWND parent, int x, int y, int width, int height)
{
HwndSourceParameters sourceParams("MFCWPFApp");
sourceParams.PositionX = x;
sourceParams.PositionY = y;
sourceParams.Height = height;
sourceParams.Width = width;
sourceParams.ParentWindow = IntPtr(parent);
sourceParams.WindowStyle = WS_VISIBLE | WS_CHILD;
m_hwndSource = gcnew HwndSource(sourceParams);
m_wpfUC = gcnew UserControl1();
m_hwndSource->RootVisual = m_wpfUC;
return (HWND) m_hwndSource->Handle.ToPointer();
}

Christian

More information:

03/21/2010

Better Together – C# and Visual Basic

C# 3 had new language extensions that are practical for every kind of application. No matter what application you’re creating, property initializers, collection initializers, Lambda expressions, LINQ… can increase productivity no matter if a Windows- or Web-application, a library, service… is created. That’s different with C# 4. The new language extensions are extremely useful for integrating with dynamic languages, .NET reflection, COM interop… Not every program created should use the dynamic keyword!

Looking at the extensions of Visual Basic 2010 it becomes very clear that a goal with C# and Visual Basic is that one language gets the features of the other. C# 3 introduced auto-properties, collection initializers, Lambda expressions… that were missing with Visual Basic. Wait, Visual Basic also had Lambda expressions. However, it was not possible to create multiline Lambdas. That’s possible now. Visual Basic 2010 also has auto-implemented properties and collection initializers.

Auto-Implemented Properties C# 3.0
public string FirstName { get; set; }
  VB 2010
Public Property FirstName As String
Collection Initializers C# 3.0
var names = new List<string>() { "James", "Jack", "Jochen" };
  VB 2010
Dim names = New List (of String) From { "James", "Jack", "Jochen"}
Implicit Line Continuation   This was never an issue with C# because ; is used. With Visual Basic 2010 now _ can be omitted.
Multiline Lambda Expressions C# 3.0
Func<int, int> expr = x =>
{
return x + 7;
}
  VB 2010
Dim expr = Function(x)
Return x + 7
End Function

Features that already have been in Visual Basic are now available in C# as well:

Optional Parameters C# 4.0
public void CreateRacer(string firstName, string lastName, int starts = 0, int wins = 0)
  VB
Public Sub CreateRacer(firstName As String, lastName As String, Optional Starts As Integer = 0, Optional Wins As Integer = 0)
Named Parameters C# 4.0
CreateRacer("Michael", "Schumacher", starts : 251, wins : 91);

  VB
CreateRacer("Michael", "Schumacher", starts := 251, wins := 91)
Dynamic C# 4.0
dynamic c = GetCalculator();
dynamic result = c.Add(3, 4);

  VB
Dim c = GetCalculator()
Dim result = c.Add(3, 4)

Dynamic allows calling into dynamic scripting languages such as Python, Ruby, JavaScript, it gives an easy way to use .NET reflection, and allows using the COM automation interfaces. Together with optional and named parameters this is really handsome! With Visual Basic 2010 the internal bindings have changed as well for interop with dynamic binders. Just the syntax of Visual Basic stayed the same with Option strict off.

C# 4 and Visual Basic 2010 also offer new features that haven’t been available with both of these languages. Among them are type equivalence support that is extremely useful with COM interop. With the /link compiler option (this is the same with both languages), COM type information can be embedded so that PIA assemblies are no longer required. Co- and contra-variance for interfaces and delegates is supported by setting the out and in keywords.

C# and Visual Basic are getting together – more and more. There’s not a lot difference in the features of these languages. The yield statement is still missing in Visual Basic – or did I miss such an enhancement in Visual Basic?

Depending on the preference of curly brackets or writing more text, the language of choice can be selected. For myself, with a background in C++ of course I prefer C#, but that’s really just a personal taste.

More information on C# 4 in my new book Professional C# 4 with .NET 4 and in my Take off to .NET 4 workshop.

Christian