<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US"><title type="html">.NET Blog</title><subtitle type="html">The .NET blog discusses new features in the .NET Framework and important issues for .NET developers.</subtitle><id>http://blogs.msdn.com/b/dotnet/atom.aspx</id><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/" /><link rel="self" type="application/atom+xml" href="http://blogs.msdn.com/b/dotnet/atom.aspx" /><generator uri="http://telligent.com" version="5.6.50428.7875">Telligent Evolution Platform Developer Build (Build: 5.6.50428.7875)</generator><updated>2013-01-03T17:25:09Z</updated><entry><title>Update to HttpClient and Automatic Decompression</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/06/19/update-to-httpclient-and-automatic-decompression.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/06/19/update-to-httpclient-and-automatic-decompression.aspx</id><published>2013-06-19T23:22:00Z</published><updated>2013-06-19T23:22:00Z</updated><content type="html">&lt;p&gt;Two weeks ago, we &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/06/06/portable-compression-and-httpclient-working-together.aspx"&gt;published&lt;/a&gt; a beta of &lt;a href="https://nuget.org/packages/Microsoft.Net.Http"&gt;HttpClient&lt;/a&gt; that provides support for automatic decompression. Since then, we&amp;rsquo;ve received a fair amount of feedback, especially around the fact that it relies on a native implementation of compression that isn&amp;rsquo;t available on the same platforms as HttpClient.&lt;/p&gt;
&lt;p&gt;Today, we&amp;rsquo;ve published another beta of HttpClient that will address those concerns.&lt;/p&gt;
&lt;h1&gt;HttpClient no longer depends on Microsoft.Bcl.Compression&lt;/h1&gt;
&lt;p&gt;In the &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/06/06/portable-compression-and-httpclient-working-together.aspx"&gt;last post&lt;/a&gt;, we explained why Microsoft.Bcl.Compression depends on native code. To recap, we are using the same implementation of &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx"&gt;DeflateStream&lt;/a&gt; that &lt;a href="http://msdn.microsoft.com/en-us/magazine/jj133817.aspx"&gt;we shipped in the .NET Framework 4.5&lt;/a&gt;. This implementation uses the de facto standard zlib, which is a native library. Unfortunately, Windows Phone 7.1 and Silverlight don't support native code (Windows Phone 8 does), which means that we couldn&amp;rsquo;t support automatic decompression on those two platforms.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/4810.Chain.jpg"&gt;&lt;img style="margin-right: auto; margin-left: auto; display: block;" src="http://blogs.msdn.com/resized-image.ashx/__size/300x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/4810.Chain.jpg" alt="" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To enable automatic decompression in HttpClient, we had three options:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Add a dependency on Microsoft.Bcl.Compression that doesn&amp;rsquo;t use native code&lt;/li&gt;
&lt;li&gt;Add a dependency on Microsoft.Bcl.Compression that uses native code&lt;/li&gt;
&lt;li&gt;Add the (managed) decompression code directly into HttpClient&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;A main benefit of using the native zlib library is the quality of compression that it provides. It&amp;rsquo;s not that we couldn&amp;rsquo;t implement a good compression algorithm in managed code &amp;ndash; the problem is that we simply don&amp;rsquo;t have one and writing one would take considerable resources and a lot more time. So we decided early on not to pursue this option for now, which leaves us with options 2 and 3.&lt;/p&gt;
&lt;p&gt;Decompression is still implemented in managed code (both in the .NET Framework 4.5 and in the Microsoft.Bcl.Compression package). Since HttpClient only needs to decompress data, it doesn&amp;rsquo;t actually depend on anything that is implemented in native code, which makes option 3 an interesting candidate.&lt;/p&gt;
&lt;p&gt;However, from an engineering perspective option 2 is cleaner, as there is no code duplication but it comes at the expense of dropping support for platforms that don&amp;rsquo;t support native code. Previously, we believed it would be better to invest in a good long term solution than to provide a less ideal implementation.&lt;/p&gt;
&lt;p&gt;Based on the feedback we received, we decided to revisit that decision and after careful consideration, we decided that the best approach is to remove the dependency on Microsoft.Bcl.Compression and add an internal copy of the managed decompression algorithms to Microsoft.Net.Http. This way, we can support automatic decompression on all platforms.&lt;/p&gt;
&lt;p&gt;This doesn&amp;rsquo;t change Microsoft.Bcl.Compression in any way &amp;ndash; it still requires native code.&lt;/p&gt;
&lt;h1&gt;Using automatic decompression on Silverlight&lt;/h1&gt;
&lt;p&gt;Before we explain how Silverlight supports automatic decompression let&amp;rsquo;s recap how automatic decompression works generally in HTTP: The client adds an HTTP request header called Accept-Encoding that specifies which compression algorithm it supports. In the response, the server can either choose to ignore that information and return an uncompressed response or compress the data in one of the algorithms the client requested. The server indicates which algorithm it used via the Content-Encoding response header. For an example with more details, see our earlier &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/06/06/portable-compression-and-httpclient-working-together.aspx"&gt;blog post on automatic decompression&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Silverlight has two networking stacks: the browser networking stack and the client networking stack. The browser networking stack supports automatic decompression. It always sets the Accept-Encoding header on each request and automatically decompresses the response.&lt;/p&gt;
&lt;p&gt;The client networking stack doesn&amp;rsquo;t have support for setting the HTTP Accept-Encoding header, but throws an exception if you try to do this manually. If you control the server, you can define your own way of activating compression, for example, by using a different HTTP header, by using a query parameter, or by simply compressing all responses. As long as the server sets the Content-Encoding header, HttpClient can automatically decompress the contents.&lt;/p&gt;
&lt;p&gt;Now let&amp;rsquo;s have a look at what that means for the automatic decompression APIs in Silverlight. The &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.supportsautomaticdecompression.aspx"&gt;SupportsAutomaticDecompression&lt;/a&gt; property will return true. The &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.automaticdecompression.aspx"&gt;AutomaticDecompression&lt;/a&gt; property is set as follows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Browser stack&lt;/strong&gt;. The value is ignored. All requests will have set the Accept-Encoding header to indicate they accept both gzip as well as deflate. Responses are automatically decompressed using the appropriate algorithm.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Client stack&lt;/strong&gt;. The value is ignored when making requests, i.e., the Accept-Encoding header will not be set. However, the Content-Encoding header will be honored when reading responses, i.e., responses are automatically decompressed using the algorithm specified by the Content-Encoding response header.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1&gt;The route to RTM&lt;/h1&gt;
&lt;p&gt;Our previously announced, but tentative, schedule looked like the following. We&amp;rsquo;ve since added about 2 weeks to these dates to accommodate the changes that I&amp;rsquo;ve described above.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style="text-decoration: line-through;"&gt;End of June&lt;/span&gt;&amp;nbsp;Early July: RC of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;li&gt;&lt;span style="text-decoration: line-through;"&gt;Mid July&lt;/span&gt;&amp;nbsp;Mid July (depending on feedback): RTM of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This schedule was based on the assumption that we wouldn&amp;rsquo;t make major changes to the features of HttpClient. Since we changed the way compression is handled, we decided to ship another beta before an RC release.&lt;/p&gt;
&lt;p&gt;This doesn&amp;rsquo;t change the schedule drastically but we expect to delay both the RC as well as the RTM by about two weeks. We want to give you as well as our partners enough time to absorb the changes and provide feedback.&lt;/p&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;The new version of HttpClient no longer depends on Microsoft.Bcl.Compression. Automatic decompression is now supported on all platforms and also allows the application to remain in the AnyCPU architecture.&lt;/p&gt;
&lt;p&gt;Microsoft.Bcl.Compression is unaffected by this change; it still isn&amp;rsquo;t supported on Windows Phone 7.1 or on Silverlight because it requires support for native code.&lt;/p&gt;
&lt;p&gt;Please let us know what you think about this update.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10427154" width="1" height="1"&gt;</content><author><name>Immo Landwerth [MSFT]</name><uri>http://blogs.msdn.com/terrajobst_4000_web.de/ProfileUrlRedirect.ashx</uri></author><category term="bcl" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/bcl/" /><category term="portable class libraries" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/portable+class+libraries/" /><category term="nuget" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/nuget/" /><category term="httpclient" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/httpclient/" /><category term="compression" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/compression/" /></entry><entry><title>NuGet Package Restore Issues</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/06/12/nuget-package-restore-issues.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/06/12/nuget-package-restore-issues.aspx</id><published>2013-06-13T00:30:00Z</published><updated>2013-06-13T00:30:00Z</updated><content type="html">&lt;p&gt;We&amp;rsquo;ve received &lt;a href="http://connect.microsoft.com/VisualStudio/feedback/details/788981/microsoft-bcl-build-targets-causes-project-loading-to-fail"&gt;several reports&lt;/a&gt; that &lt;a href="http://blogs.msdn.com/b/dotnet/archive/tags/nuget/"&gt;our NuGet packages&lt;/a&gt; broke the &lt;a href="http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages"&gt;NuGet package restore feature&lt;/a&gt;. In this post, I&amp;rsquo;ll explain what the issue is, how you can work around it, and finally how we plan on fixing this issue in the long term.&lt;/p&gt;
&lt;h1&gt;The problem and solution&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;Microsoft.Bcl.Build&lt;/strong&gt; and &lt;strong&gt;Microsoft.Bcl.Compression&lt;/strong&gt; require custom target files, which do not work well with NuGet&amp;rsquo;s package restore feature. The easiest way to fix the package restore issues is by checking in any .targets files that are stored under the packages directory.&lt;/p&gt;
&lt;h1&gt;What&amp;rsquo;s package restore?&lt;/h1&gt;
&lt;p&gt;When you add a NuGet package to your project, NuGet essentially does two things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;It downloads the package and puts it in your solution under a directory called &amp;ldquo;packages&amp;rdquo;.&lt;/li&gt;
&lt;li&gt;It installs the package to your project. This will add references to additional framework assemblies, references to assemblies provided by the NuGet package, add additional content to your project and last, but not least, import any custom target files. Of course, not all NuGet packages use all those features.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In order to build your project on a build server you have to check in all sources as well as all 3rd party libraries. Many developers cringe when binaries need to be checked in to version control as they typically aren&amp;rsquo;t stored very efficiently and cause bloat over time. This is especially problematic for distributed version control systems (DVCS) like git or Mercurial where developers have to download the repository with the entire history (typically referred to as &amp;ldquo;cloning&amp;rdquo;).&lt;/p&gt;
&lt;p&gt;For that reason NuGet has a feature called &lt;a href="http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages"&gt;package restore&lt;/a&gt;. You need to enable that feature explicitly by right-clicking your solution and invoking the &lt;strong&gt;Enable NuGet Package Restore&lt;/strong&gt; menu item:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/300x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/2541.EnablePackageRestore.png" alt="" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;After package restore is enabled you can delete the &amp;ldquo;packages&amp;rdquo; directory from your solution. Rebuilding the project will automatically re-create this directory and retrieve all missing packages; whether they are downloaded from the internet or a local file share. This allows excluding the packages directory from version control as the build machine can retrieve the packages and thus doesn&amp;rsquo;t need a checked-in version of the NuGet packages.&lt;/p&gt;
&lt;h1&gt;What&amp;rsquo;s the issue?&lt;/h1&gt;
&lt;p&gt;Two of our packages provide a custom targets file:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Microsoft.Bcl.Build&lt;/li&gt;
&lt;li&gt;Microsoft.Bcl.Compression&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Targets files are MSBuild files that provide additional functionality that extend the build process. We use it for several features for which NuGet doesn&amp;rsquo;t provide declarative features today, for example, binding redirects and choosing the correct binary for the selected architecture. We also use it for additional diagnostics, as explained in this &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/06/06/portable-compression-and-httpclient-working-together.aspx"&gt;blog post&lt;/a&gt; (section &amp;ldquo;The CPU architecture matters&amp;rdquo;).&lt;/p&gt;
&lt;p&gt;Installing Microsoft.Bcl.Build will change your project by adding an &amp;lt;import&amp;gt; entry for the target file to your project. The target file is located in the packages folder&lt;/p&gt;
&lt;pre&gt;&amp;lt;Import Project="..\packages\Microsoft.Bcl.Build.1.0.7\tools\Microsoft.Bcl.Build.targets" /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;If package restore is enabled, it&amp;rsquo;s likely the packages folder is excluded so the .targets file isn&amp;rsquo;t available on the build machine. You may now think &amp;ldquo;hold on &amp;ndash; isn&amp;rsquo;t package restore supposed to take care of this?&amp;rdquo; Unfortunately, not in this case. In order to restore packages you need to build the project, since package restore is plugged into the build process. Before building a project MSBuild loads the project, which in turn requires loading all necessary .targets files. Since the .targets files can&amp;rsquo;t be located at load time the build fails well before package restore has a chance of executing. You will see an error message like this:&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;span style="color: #ff0000;"&gt;YourProject.csproj(44,3): error MSB4019: The imported project "D:\YourProject.csproj\packages\Microsoft.Bcl.Build.1.0.7\tools\Microsoft.Bcl.Build.targets" was not found. Confirm that the path in the &amp;lt;Import&amp;gt; declaration is correct, and that the file exists on disk.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;You may be aware that NuGet 2.5 added &lt;a href="http://docs.nuget.org/docs/release-notes/nuget-2.5#Automatic_import_of_msbuild_targets_and_props_files"&gt;first class support for installing custom target files&lt;/a&gt;. The end result is very similar, except that the import looks like this:&lt;/p&gt;
&lt;pre&gt;&amp;lt;Import Project="..\packages\Microsoft.Bcl.Build.1.0.7\tools\Microsoft.Bcl.Build.targets"
        Condition="Exists(&amp;lsquo;..\packages\Microsoft.Bcl.Build.1.0.7\tools\Microsoft.Bcl.Build.targets&amp;rsquo;)" /&amp;gt;
&lt;/pre&gt;
&lt;p&gt;The import is conditioned on the existence of the file which allows loading the project file even if the .targets file doesn&amp;rsquo;t exist. Unfortunately this doesn&amp;rsquo;t solve the problem either.&lt;/p&gt;
&lt;p&gt;On the build machine, the build will load the project without our .targets file, run package restore and then build the project. Since MSBuild evaluates all &amp;lt;import&amp;gt; entries before building, the .targets files don&amp;rsquo;t participate in the build because they weren&amp;rsquo;t present when the project was loaded. Depending on what a custom .targets file does this can have virtually any impact on the build, for example the build may simply still fail or &amp;ndash; worse &amp;ndash; succeed with incorrect outputs. For that reason we decided to not use conditional imports because the build at least fails in a deterministic and predictable way.&lt;/p&gt;
&lt;p&gt;On the developer machine you have a very similar problem. When a project has missing .targets files it will not successfully open in Visual Studio. You might think that conditional imports would be a good solution there but you&amp;rsquo;ve fundamentally the same problem as on the build machine: the first build will restore the packages but the build outputs might be bogus without yielding an error. This behavior would remain until you re-open the solution. This issue would be quite hard to diagnose.&lt;/p&gt;
&lt;h1&gt;Workarounds&lt;/h1&gt;
&lt;p&gt;In order to make package restore work for packages that have custom target files you have three options:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Stop using package restore and check-in all package files&lt;/li&gt;
&lt;li&gt;Explicitly run package restore before building the project&lt;/li&gt;
&lt;li&gt;Check-in the .targets files&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The first option isn&amp;rsquo;t a really an option and we certainly wouldn&amp;rsquo;t recommend it either.&lt;/p&gt;
&lt;p&gt;The second option requires changing the way your build is hooked up to your build environment. You need to run nuget.exe to restore packages before you actually run MSBuild on your solution:&lt;/p&gt;
&lt;pre&gt;        nuget.exe install .\PortableClassLibrary3\packages.config
&lt;/pre&gt;
&lt;p&gt;This ensures that by the time MSBuild loads the project all .targets are already present.&lt;/p&gt;
&lt;p&gt;The third option is the easiest solution as it doesn&amp;rsquo;t require any changes to your environment. You only need to check-in the .targets files &amp;ndash; you don&amp;rsquo;t need to check in any other files from the packages directory. Since target files are simply text files, they aren&amp;rsquo;t causing the repository to bloat over time. This also solves the issue on the developer&amp;rsquo;s machine whereby the second option would still require each team member to run package restore before the affected projects can be opened in Visual Studio.&lt;/p&gt;
&lt;p&gt;We are working with the NuGet team to make sure we don&amp;rsquo;t have to use .target files moving forward. The idea is to add some features that allow packages to be declarative as opposed to adding code that runs during the build.&lt;/p&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;We understand that this isn&amp;rsquo;t good long term solution and are working with NuGet to greatly reduce the need for custom .targets files.&lt;/p&gt;
&lt;p&gt;Please let us know if you have any questions or additional concerns.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10425516" width="1" height="1"&gt;</content><author><name>Immo Landwerth [MSFT]</name><uri>http://blogs.msdn.com/terrajobst_4000_web.de/ProfileUrlRedirect.ashx</uri></author><category term="bcl" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/bcl/" /><category term="nuget" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/nuget/" /></entry><entry><title>Portable Compression and HttpClient Working Together</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/06/06/portable-compression-and-httpclient-working-together.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/06/06/portable-compression-and-httpclient-working-together.aspx</id><published>2013-06-07T02:08:00Z</published><updated>2013-06-07T02:08:00Z</updated><content type="html">&lt;p&gt;Today we&amp;rsquo;re happy to announce that we released two NuGet packages:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;A brand new &lt;a href="https://nuget.org/packages/Microsoft.Bcl.Compression"&gt;Microsoft.Bcl.Compression&lt;/a&gt; (Beta)&lt;/strong&gt;. A portable compression library that supports stream based compression (gzip, deflate) as well as ZIP archives.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;An updated &lt;a href="https://nuget.org/packages/Microsoft.Net.Http"&gt;Microsoft.Net.Http&lt;/a&gt; 2.2 (Beta)&lt;/strong&gt;. &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/05/29/get-httpclient-rtm-200-ok.aspx"&gt;Last week we shipped an RTM version&lt;/a&gt;. Today, we released a new beta that provides automatic decompression by taking a dependency on the Microsoft.Bcl.Compression package.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Before we go into the details, let&amp;rsquo;s first take a look at why compression is particularly interesting for &lt;strong&gt;HttpClient&lt;/strong&gt;.&lt;/p&gt;
&lt;h1&gt;Compression and HttpClient&lt;/h1&gt;
&lt;p&gt;We live in a world where we are permanently surrounded by devices, particularly smart phones. Apps that run on these devices are often not super useful in isolation; they require services to provide data and enhance their features.&lt;/p&gt;
&lt;p&gt;As a result many developers use the &lt;strong&gt;HttpClient&lt;/strong&gt; class to access web resources such as REST services. Most service providers want to minimize the data that is being transmitted between a client and server. This is particularly helpful when services are accessed by apps on mobile devices that use metered Internet connections. The cost to use the app is directly affected by the amount of data being transmitted, and less data means lower cost to the end-user.&lt;/p&gt;
&lt;p&gt;In HTTP, headers provide a way to negotiate capabilities between the client and server. The &lt;strong&gt;Accept-Encoding&lt;/strong&gt; header allows clients to tell the server that they support reading the response in a compressed format (e.g., gzip or Deflate), and is a logical step when using HTTP from a mobile client. The server may choose to ignore the header or reply in another format the client indicates support for.&lt;/p&gt;
&lt;p&gt;Not surprisingly, &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx"&gt;after we announced a portable HttpClient&lt;/a&gt;, you asked us to support the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.automaticdecompression.aspx"&gt;AutomaticDecompression property&lt;/a&gt; on &lt;a href="http://msdn.microsoft.com/en-us/library/hh193540.aspx"&gt;HttpClientHandler&lt;/a&gt;, particularly for Windows Phone apps. Unfortunately, at the time, we didn&amp;rsquo;t have a portable compression library at our disposal.&lt;/p&gt;
&lt;p&gt;In this blog post, I&amp;rsquo;d like to show you our new portable compression library and explain how we leverage it to support &lt;strong&gt;AutomaticDecompression&lt;/strong&gt; in &lt;strong&gt;HttpClient&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/180x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/7457.Compressor.png" alt="" border="0" /&gt;&lt;/p&gt;
&lt;h1&gt;Enter Microsoft.Bcl.Compression&lt;/h1&gt;
&lt;p&gt;Today we released a beta of &lt;a href="https://nuget.org/packages/Microsoft.Bcl.Compression/"&gt;Microsoft.Bcl.Compression&lt;/a&gt;, a NuGet package that provides compression APIs in a &lt;a href="http://msdn.microsoft.com/en-us/library/gg597391.aspx"&gt;portable class library&lt;/a&gt;. The compression support covers the following aspects:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Compression streams (&lt;a href="http://msdn.microsoft.com/en-us/library/system.io.compression.deflatestream.aspx"&gt;Deflate&lt;/a&gt; &amp;amp; &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx"&gt;gzip&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Reading and writing &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.aspx"&gt;ZIP archives&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We also released an update to our &lt;a href="https://nuget.org/packages/Microsoft.Net.Http/"&gt;HttpClient NuGet package&lt;/a&gt; that takes a dependency on Microsoft.Bcl.Compression to support automatic decompression.&lt;/p&gt;
&lt;p&gt;The Microsoft.Bcl.Compression NuGet package is supported on the following platforms:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;.NET Framework 4.5&lt;/li&gt;
&lt;li&gt;Windows Phone 8&lt;/li&gt;
&lt;li&gt;.NET for Windows Store apps&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This package also includes portable class libraries that target any of those platforms.&lt;/p&gt;
&lt;p&gt;The platform list is different from the platforms supported by &lt;strong&gt;HttpClient&lt;/strong&gt;. In particular, &lt;strong&gt;HttpClient&lt;/strong&gt; supports the .NET Framework 4 and Windows Phone 7.5, but&amp;nbsp;the Microsoft.Bcl.Compression package isn&amp;rsquo;t supported on&amp;nbsp;those&amp;nbsp;platforms.&lt;/p&gt;
&lt;h1&gt;Using Microsoft.Bcl.Compression directly&lt;/h1&gt;
&lt;p&gt;Of course, a portable compression library has plenty of uses other than just reducing the footprint of networking requests. That's why Microsoft.Bcl.Compression is completely independent from HttpClient and can be used directly. Let&amp;rsquo;s have a look at how you would use it.&lt;/p&gt;
&lt;p&gt;Consider a Windows Phone app that shows a random poem from a collection of poems. The poems are represented as text files. In order to keep the app small, we compressed all poems using &lt;a href="http://en.wikipedia.org/wiki/Gzip"&gt;gzip&lt;/a&gt;. During application startup, a random poem is selected and read from the application data. In order to decompress the contents of the poem, we use the &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx"&gt;GZipStream class&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;        private static string ReadRandomPoem()
        {
            int randomPoemNumber = 42; // Super random
            string poemName = string.Format("Poem{0}.txt.gz", randomPoemNumber);
            using (Stream stream = OpenApplicationFile(poemName))
            using (Stream decompressed = new GZipStream(stream, CompressionMode.Decompress))
            using (StreamReader reader = new StreamReader(decompressed))
            {
                string text = reader.ReadToEnd();
                return text;
            }
        }
&lt;/pre&gt;
&lt;p&gt;Now let&amp;rsquo;s say that in the next version of the app we allow the user to select a &lt;a href="http://en.wikipedia.org/wiki/Category:Poetic_form"&gt;form of poem&lt;/a&gt;, such as sonnet or haiku. To implement this, we decide to store all poems that share the same form in the same &lt;a href="http://en.wikipedia.org/wiki/ZIP_archive"&gt;ZIP archive&lt;/a&gt;. To read a ZIP archive we use the &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.aspx"&gt;ZipArchive class&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;        private static string ReadRandomPoem()
        {
            int randomPoemNumber = 42; // Still super random
            string poemName = string.Format("Poem{0}.txt", randomPoemNumber);
            using (Stream archiveStream = OpenApplicationFile("haikus.zip"))
            using (ZipArchive archive = new ZipArchive(archiveStream, ZipArchiveMode.Read))
            {
                ZipArchiveEntry zipArchiveEntry = archive.GetEntry(poemName);
                using (Stream stream = zipArchiveEntry.Open())
                using (StreamReader reader = new StreamReader(stream))
                {
                    string text = reader.ReadToEnd();
                    return text;
                }
            }
        }
&lt;/pre&gt;
&lt;h1&gt;Using automatic decompression with HttpClient&lt;/h1&gt;
&lt;p&gt;Now let&amp;rsquo;s have look at how you would use the decompression APIs with HttpClient.&lt;/p&gt;
&lt;p&gt;First, automatic decompression is not enabled by default for HttpClient. To use it, you need to set the&lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.automaticdecompression.aspx"&gt; AutomaticDecompression property&lt;/a&gt; on &lt;a href="http://msdn.microsoft.com/en-us/library/hh193540.aspx"&gt;HttpClientHandler to GZip or Deflate&lt;/a&gt;. This API follows the optional feature pattern; meaning it exposes an API that indicates whether a particular feature is supported. Automatic decompression support is indicated with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.supportsautomaticdecompression.aspx"&gt;SupportsAutomaticDecompression property&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If an implementation of &lt;strong&gt;HttpClient&lt;/strong&gt; doesn&amp;rsquo;t support automatic decompression, it returns &lt;strong&gt;false&lt;/strong&gt; from the &lt;strong&gt;SupportsAutomaticDecompression&lt;/strong&gt; property and throws a &lt;strong&gt;NotSupportedException&lt;/strong&gt; from the setter and getter for the &lt;strong&gt;AutomaticDecompression&lt;/strong&gt; property. This was how our previous release of the &lt;strong&gt;HttpClient&lt;/strong&gt; NuGet package behaved.&lt;/p&gt;
&lt;p&gt;With this pattern in mind, using automatic decompression looks like this:&lt;/p&gt;
&lt;pre&gt;        var handler = new HttpClientHandler();
        if (handler.SupportsAutomaticDecompression)
        {
            handler.AutomaticDecompression = DecompressionMethods.GZip |
                                             DecompressionMethods.Deflate;
        }
        var httpClient = new HttpClient(handler);
        var str = await httpClient.GetStringAsync("http://en.wikipedia.org/wiki/Gzip");   &lt;/pre&gt;
&lt;p&gt;The request then provides the additional Accept-Encoding header:&lt;/p&gt;
&lt;pre&gt;        GET http://en.wikipedia.org/wiki/Gzip HTTP/1.1
        Host: en.wikipedia.org
        &lt;span style="background-color: #ffff00;"&gt;Accept-Encoding: gzip, deflate&lt;/span&gt;
        Connection: Keep-Alive
&lt;/pre&gt;
&lt;p&gt;Servers that choose to support it will respond and indicate the compression algorithm they used. In this example, the server compressed the body using gzip:&lt;/p&gt;
&lt;pre&gt;        HTTP/1.1 200 OK
        Server: nginx/1.1.19
        Date: Wed, 13 Mar 2013 14:04:24 GMT
        Content-Type: text/html; charset=UTF-8
        Content-Length: 17765
        Connection: keep-alive
        X-Content-Type-Options: nosniff
        Content-Language: en
        Last-Modified: Tue, 05 Mar 2013 03:38:51 GMT
        &lt;span style="background-color: #ffff00;"&gt;Content-Encoding: gzip&lt;/span&gt;
        Expires: Thu, 01 Jan 1970 00:00:00 GMT
        Cache-Control: private, s-maxage=0, max-age=0, must-revalidate
        Vary: Accept-Encoding,Cookie
        Age: 179
    &lt;/pre&gt;
&lt;p&gt;The &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpcontent.createcontentreadstreamasync.aspx"&gt;response stream&lt;/a&gt; that &lt;strong&gt;HttpClient&lt;/strong&gt; returns to you will automatically decompress the result using the appropriate algorithm. On my machine I got the following results:&lt;/p&gt;
&lt;p&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/7360.Graph.png" alt="" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;This yields to a reduction by 77%&lt;/strong&gt;. Needless to say, the actual results depend on the request and how well it compresses. So your results will naturally vary.&lt;/p&gt;
&lt;h1&gt;The CPU architecture matters&lt;/h1&gt;
&lt;p&gt;In the .NET Framework 4.5 &lt;a href="http://msdn.microsoft.com/en-us/magazine/jj133817.aspx"&gt;we changed our DeflateStream implementation&lt;/a&gt; to use the popular zlib library. As a result, DeflateStream provides a better implementation of the deflate algorithm and, in most cases, a better compression than in earlier versions of the .NET Framework.&lt;/p&gt;
&lt;p&gt;Microsoft.Bcl.Compression also uses the deflate algorithm, which is implemented in native code. This means that Microsoft.Bcl.Compression requires CPU-specific binaries, and each project that consumes it has to be CPU specific. Given that some of the platforms the Microsoft.Bcl.Compression package supports already provide built-in support for compression, only Windows Phone projects are affected by this requirement.&lt;/p&gt;
&lt;p&gt;However, we&amp;rsquo;ve found a way to avoid making &lt;em&gt;&lt;strong&gt;each&lt;/strong&gt;&lt;/em&gt; project CPU-specific:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Class library projects that consume Microsoft.Bcl.Compression can remain Any CPU. This makes them consumable by other &lt;strong&gt;Any CPU&lt;/strong&gt; projects as well as CPU-specific projects.&lt;/li&gt;
&lt;li&gt;Windows Phone application projects that use Microsoft.Bcl.Compression (either directly or indirectly via another class library) must add a NuGet reference to Microsoft.Bcl.Compression, and specify either &lt;strong&gt;ARM&lt;/strong&gt; or &lt;strong&gt;x86&lt;/strong&gt; architecture, for phone or emulator respectively. This ensures we deploy binaries that match the CPU architecture of the application.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We understand that this can be tricky to get right. Therefore, our NuGet package will guide you through the process. Let&amp;rsquo;s assume that you have a solution with the following two projects:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Windows Phone App (configured as Any CPU)&lt;/li&gt;
&lt;li&gt;Portable class library (configured as Any CPU)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Let&amp;rsquo;s say the portable class library depends on Microsoft.Bcl.Compression, whereas the phone app doesn&amp;rsquo;t depend on Microsoft.Bcl.Compression but does depend on the portable class library.&lt;/p&gt;
&lt;p&gt;Building the solution will yield the following error message:&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;em&gt;Phone Application: Project must install NuGet package Microsoft.Bcl.Compression.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;After adding the reference to Microsoft.Bcl.Compression and rebuilding your app, a new MSBuild task (which comes with the NuGet package) will deploy CPU-specific binaries as dependencies of your app. If your app is configured as Any CPU, the build will fail again with this error message:&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;em&gt;Phone Application: Microsoft.Bcl.Compression does not support the currently selected platform of 'AnyCPU'. The supported platforms are 'x86' and 'ARM'.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;The project should build successfully after you change the platform target to X86 or ARM.&lt;/p&gt;
&lt;p&gt;We&amp;rsquo;d love to hear your feedback around this!&lt;/p&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;We've released a beta version of the new &lt;a href="https://nuget.org/packages/Microsoft.Bcl.Compression/"&gt;Microsoft.Bcl.Compression&lt;/a&gt; package that provides portable compression support for your apps. When you're using portable compression, don&amp;rsquo;t forget to set your CPU architecture for Windows Phone projects. And as you saw earlier: even if you forget it, our package will take care of reminding you.&lt;/p&gt;
&lt;p&gt;We've also released a new beta for the existing &lt;a href="https://nuget.org/packages/Microsoft.Net.Http/"&gt;Microsoft.Net.Http&lt;/a&gt; package in version 2.2. It adds support for &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.automaticdecompression.aspx"&gt;AutomaticDecompression&lt;/a&gt;. Since this added substantial functionality to HttpClient, we decided to ship a beta instead of updating &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/05/29/get-httpclient-rtm-200-ok.aspx"&gt;the stable release we shipped a week ago&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here is our tentative release schedule for turning Microsoft.Net.Http 2.2 into a stable release:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;End of June: RC of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;li&gt;Around July (depending on feedback): RTM of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This timeline depends on your feedback. So please let us know what you think of Microsoft.Bcl.Compression, and how the new version of HttpClient works for you!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10424285" width="1" height="1"&gt;</content><author><name>Immo Landwerth [MSFT]</name><uri>http://blogs.msdn.com/terrajobst_4000_web.de/ProfileUrlRedirect.ashx</uri></author><category term="bcl" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/bcl/" /><category term="portable class libraries" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/portable+class+libraries/" /><category term="nuget" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/nuget/" /><category term="httpclient" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/httpclient/" /><category term="compression" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/compression/" /></entry><entry><title>Get /httpclient/rtm – 200 OK</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/05/29/get-httpclient-rtm-200-ok.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/05/29/get-httpclient-rtm-200-ok.aspx</id><published>2013-05-29T18:48:00Z</published><updated>2013-05-29T18:48:00Z</updated><content type="html">&lt;p&gt;As promised in our &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/05/22/portable-httpclient-is-now-available-as-rc.aspx"&gt;last blog post&lt;/a&gt; we&amp;rsquo;re releasing &lt;a href="http://nuget.org/packages/Microsoft.Net.Http"&gt;Microsoft.Net.Http&lt;/a&gt; as a stable NuGet package today. Yep, that&amp;rsquo;s right: You can finally start using the portable HttpClient 2.1 in production!&lt;/p&gt;
&lt;p&gt;As we&amp;rsquo;ve discussed in previous blog posts, HttpClient is a modern networking API which makes it easy to access any resource exposed through HTTP. The HttpClient API has been available in some versions of .NET for a while now. This NuGet package makes a standard set of HttpClient APIs available across a wider array of platforms, including Windows Phone 7.5 and higher, .NET Framework 4.0 and higher, and Windows Store. This enables&amp;nbsp;you to share more .NET code across these platforms.&lt;/p&gt;
&lt;p&gt;This package also addresses one of the top User Voice requests for .NET: providing an HttpClient implementation for Portable Class Libraries (and therefore also on Windows Phone 8).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;a href="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3158400-add-httpclient-in-portable-class-library-pcl-?tracking_code=02eea86a2711ee54158af1caf8ff21a1"&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/5756.UserVoice.png" alt="" border="0" /&gt;&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We closed this request when we posted the preview of the new HttpClient back in February. Now, with the release of a stable version, we&amp;rsquo;re excited that&amp;nbsp;you now&amp;nbsp;have a high-quality implementation to use and build on in your .NET projects.&lt;/p&gt;
&lt;p&gt;This package requires Visual Studio 2010 or Visual Studio 2012, and NuGet package manager 2.5 or higher.&lt;/p&gt;
&lt;h1&gt;Changes from RC&lt;/h1&gt;
&lt;p&gt;We haven&amp;rsquo;t changed much since last week's release candidate (RC), but this is by-design. For our NuGet packages, feature work is first released in beta builds only. Once we think we matured a feature enough (based on internal testing as well as customer feedback), we release an RC. If there aren&amp;rsquo;t any major bugs, we turn (generally the same) bits into an RTM, which NuGet calls a stable release. This process helps ensure that we ship high-quality components.&lt;/p&gt;
&lt;p&gt;We did make some very minor changes to our package metadata:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;To make the package easier to recognize as an official Microsoft component, we prefixed it with &amp;ldquo;Microsoft&amp;rdquo;.&lt;/li&gt;
&lt;li&gt;To improve search results, we added tags (e.g., &amp;ldquo;HTTP&amp;rdquo; and &amp;ldquo;REST&amp;rdquo;).&lt;/li&gt;
&lt;/ol&gt;
&lt;h1&gt;What&amp;rsquo;s next for HttpClient?&lt;/h1&gt;
&lt;p&gt;As I explained in my &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2013/05/22/portable-httpclient-is-now-available-as-rc.aspx"&gt;last blog post&lt;/a&gt;, the current release doesn&amp;rsquo;t include support for automatic decompression. One of our readers commented that each time a web request is issued without &lt;a href="http://en.wikipedia.org/wiki/Gzip"&gt;gzip&lt;/a&gt; support, it hurts baby seals.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/300x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/3817.BabySeal.jpg" alt="" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;We know automatic compression is an important feature for you, and we care deeply about the health of baby seals, so we are working on a portable compression library that provides this feature. Our plan is to ship a beta release of HttpClient 2.2 that includes this library very soon. As a reminder, here is our tentative release schedule:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Mid-June: Beta of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;li&gt;End of June: RC of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;li&gt;Around July (depending on feedback): RTM of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;/ol&gt;
&lt;h1&gt;Community support for automatic compression&lt;/h1&gt;
&lt;p&gt;Until we release a stable version of automatic decompression that you can use in production, there are some alternatives you may want to consider. (Please note this isn&amp;rsquo;t intended to be a complete list. If you&amp;rsquo;ve developed a similar feature, let us know by posting a comment below.)&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href="http://social.microsoft.com/Profile/Morten%20Nielsen/activity"&gt;Morten Nielsen&lt;/a&gt;, a Microsoft Valued Professional (MVP), has provided an implementation of &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.aspx"&gt;HttpClientHandler&lt;/a&gt; that has support for &lt;a href="http://en.wikipedia.org/wiki/Gzip"&gt;gzip&lt;/a&gt; compression. You can find the source code here:&lt;/p&gt;
&lt;p&gt;&lt;a href="https://gist.github.com/dotMorten/4981198"&gt;https://gist.github.com/dotMorten/4981198&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;a href="https://twitter.com/robertmclaws"&gt;Robert McLaws&lt;/a&gt; created a &lt;a href="https://github.com/advancedrei/HttpClient.Compression"&gt;derived project&lt;/a&gt; and packaged it up as a NuGet package. You can install &lt;a href="http://nuget.org/packages/HttpClient.Compression"&gt;his NuGet package&lt;/a&gt; either via the package manager console:&lt;/p&gt;
&lt;pre&gt;                Install-Package HttpClient.Compression &amp;ndash;Pre&lt;/pre&gt;
&lt;p&gt;or by searching for &lt;strong&gt;HttpClient.Compression&lt;/strong&gt; in the NuGet Package Manager dialog. At the time of this writing, HttpClient.Compression wasn&amp;rsquo;t available as a stable NuGet package, because the stable version of our HttpClient wasn&amp;rsquo;t released yet. I&amp;rsquo;m sure it will get updated very soon, though.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;HttpClient 2.1 is now available as a stable release on NuGet. The license allows its use in production and unblocks third parties from building stable NuGet components on top of it.&lt;/p&gt;
&lt;p&gt;You can expect a beta release of HttpClient 2.2 with support for automatic decompression very soon. Meanwhile, help protect baby seals by using one of community libraries we linked to above. If there are other community libraries available, please let us know in the comments section!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10422148" width="1" height="1"&gt;</content><author><name>Immo Landwerth [MSFT]</name><uri>http://blogs.msdn.com/terrajobst_4000_web.de/ProfileUrlRedirect.ashx</uri></author><category term="bcl" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/bcl/" /><category term="portable class libraries" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/portable+class+libraries/" /><category term="nuget" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/nuget/" /></entry><entry><title>Portable HttpClient is now available as RC</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/05/22/portable-httpclient-is-now-available-as-rc.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/05/22/portable-httpclient-is-now-available-as-rc.aspx</id><published>2013-05-23T00:24:00Z</published><updated>2013-05-23T00:24:00Z</updated><content type="html">&lt;p&gt;Three months ago &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx"&gt;we shipped the first preview of the portable HttpClient&lt;/a&gt;. Many of you wondered when we would ship the RTM version. Today, we&amp;rsquo;re happy to announce the first step towards an RTM: We shipped a release candidate (RC) of HttpClient (&lt;a href="http://nuget.org/packages/Microsoft.Net.Http/"&gt;Microsoft.Net.Http package on NuGet&lt;/a&gt;) that includes all the bug fixes since the preview.&lt;/p&gt;
&lt;h1&gt;New features&lt;/h1&gt;
&lt;p&gt;To address some of the platform differences in a portable fashion, we&amp;rsquo;ve added new&amp;nbsp;capability APIs.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;HttpClientHandler.SupportsUseProxy()&lt;/strong&gt;: The existing &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.supportsproxy.aspx"&gt;HttpClientHandler.SupportsProxy&lt;/a&gt; property indicates whether both the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.useproxy.aspx"&gt;UseProxy&lt;/a&gt; property and the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.proxy.aspx"&gt;Proxy&lt;/a&gt; property are supported. This created an issue because some platforms (for example, Windows Phone) don&amp;rsquo;t allow you to configure a proxy explicitly. However, Windows Phone lets you control whether the machine wide proxy should be used. To model this behavior, we added the &lt;strong&gt;HttpClientHandler.SupportsUseProxy()&lt;/strong&gt; extension method. For some platforms that don&amp;rsquo;t support both, such as Windows Phone, the &lt;strong&gt;SupportsProxy&lt;/strong&gt; property will continue to return false, but the &lt;strong&gt;SupportsUseProxy()&lt;/strong&gt; method will return true.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;HttpClientHandler.SupportsAllowAutoRedirect()&lt;/strong&gt;: The &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.supportsredirectconfiguration.aspx"&gt;HttpClientHandler.SupportsRedirectConfiguration&lt;/a&gt; property had a similar issue: It controls whether both the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.allowautoredirect.aspx"&gt;AllowAutoRedirect&lt;/a&gt; and the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.maxautomaticredirections.aspx"&gt;MaxAutomaticRedirections&lt;/a&gt; properties are supported. Windows Phone doesn&amp;rsquo;t support specifying the maximum number of automatic redirections, but it does support redirection. For that reason, we added the &lt;strong&gt;HttpClientHandler.SupportsAllowAutoRedirect()&lt;/strong&gt; extension method.&lt;/p&gt;
&lt;p&gt;Here's how you use these capability APIs:&lt;/p&gt;
&lt;pre&gt;HttpClientHandler handler = new HttpClientHandler();

// Configure proxy (if supported)
if (handler.SupportsUseProxy())
    handler.UseProxy = true;

// Allow automatic redirection (if supported)
if (handler.SupportsAllowAutoRedirect())
    handler.AllowAutoRedirect = true;&lt;/pre&gt;
&lt;p&gt;In case you are wondering why we added extension methods instead of regular properties: Some of the platforms that &lt;strong&gt;Microsoft.Net.Http&lt;/strong&gt; supports already provide the &lt;strong&gt;HttpClientHandler&lt;/strong&gt; class, which is used on those platforms. Since we can&amp;rsquo;t modify the built-in version of the properties directly, we added extension methods that ship in a separate assembly with the NuGet package.&lt;/p&gt;
&lt;h1&gt;Bug fixes&lt;/h1&gt;
&lt;p&gt;All bug fixes are listed in the &lt;a href="http://blogs.msdn.com/b/bclteam/p/httpclient.aspx"&gt;release notes&lt;/a&gt;. In this post, I&amp;rsquo;d like to highlight just one:&lt;/p&gt;
&lt;p style="padding-left: 30px;"&gt;&lt;em&gt;Issue: When consuming a portable class library that depends on HttpClient from a Windows Store application, the app can crash with a MissingMethodException.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We&amp;rsquo;ve fixed this bug by using the technique we explained in our &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2013/04/17/microsoft-bcl-async-is-now-stable.aspx"&gt;blog post about Microsoft.Bcl.Async&lt;/a&gt;: We ensure during the build that the application has a reference to the NuGet package.&lt;/p&gt;
&lt;h1&gt;Future directions&lt;/h1&gt;
&lt;p&gt;This RC doesn&amp;rsquo;t include support for the &lt;a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.automaticdecompression.aspx"&gt;HttpClientHandler.AutomaticDecompression&lt;/a&gt; property. Many of you have asked for this support, and we certainly haven&amp;rsquo;t ignored it or forgotten about it. In fact, &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/wptools/thread/1fa78fca-5aae-436b-a9c0-0bafa5b78b14/#5667f6af-21c5-4224-b2c3-400729bfbf14"&gt;our original plan was&lt;/a&gt; to ship another preview with support for automatic decompression, and then ship an RTM version a few weeks later. So why did we change our minds about it?&lt;/p&gt;
&lt;p&gt;We had two options:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Block the release of HttpClient until automatic decompression is ready.&lt;/li&gt;
&lt;li&gt;Ship an interim release of HttpClient that doesn&amp;rsquo;t have automatic decompression but is marked as a stable NuGet release and comes with a license that allows usage in production.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We decided to go with the second option, because we believe it delivers functionality sooner to our customers. After all, that's why we ship on NuGet, and we hope you agree.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s recap why our team is investing so much in releasing components via NuGet. The reason is twofold:&lt;/p&gt;
&lt;p&gt;First, it allows bridging differences in functionality between platforms we already shipped. A good example is HttpClient, and also includes the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2013/04/17/microsoft-bcl-async-is-now-stable.aspx"&gt;support for the async and await keywords&lt;/a&gt;. Shipping features out of band also enables us to ship new functionality for multiple platforms via a single portable class library, without having to wait for any of the platforms to add that functionality.&lt;/p&gt;
&lt;p&gt;Second, our goal is to strengthen the feedback loop with you, our customers. In the past, we&amp;rsquo;ve shipped &amp;ldquo;big&amp;rdquo; betas, like a beta of the entire .NET Framework. This approach certainly has some advantages, but we&amp;rsquo;ve seen issues with it as well. The biggest downside is that &amp;ldquo;big&amp;rdquo; betas are pretty expensive to ship and are typically very close to RTM, which, in turn, means that we can&amp;rsquo;t make impactful changes anymore. In fact, we have to turn down a large number of the bug reports we get in &amp;ldquo;big&amp;rdquo; betas, either because they affect a relatively small number of customers or because fixing the bugs would place the RTM release at risk. We&amp;rsquo;re certainly not the first company running into this problem; there is an entire agile software development movement in our industry that focuses on this. I don&amp;rsquo;t want to go into a philosophical discussion about agile methodologies, but it&amp;rsquo;s pretty hard to disagree that shipping early and often helps with feedback loop issues.&lt;/p&gt;
&lt;p&gt;A good example where we use your feedback quite heavily is in the previews of i&lt;a href="http://blogs.msdn.com/b/bclteam/archive/tags/immutable/"&gt;mmutable collections&lt;/a&gt;; in contrast to &amp;ldquo;big&amp;rdquo; betas, we were able to change the design of the APIs when we believe that&amp;rsquo;s the correct approach.&lt;/p&gt;
&lt;p&gt;Unfortunately, shipping a constant stream of previews isn&amp;rsquo;t necessarily a helpful solution in all scenarios. On certain platforms, such as the .NET Framework 4.5 and Windows Store, HttpClient is already available as a fully supported, RTM-quality component. For that reason, we can offer a preview of HttpClient only for Windows Phone today.&lt;/p&gt;
&lt;p&gt;Here are our tentative plans for future NuGet releases of HttpClient:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Today: RC of HttpClient 2.1.&lt;/li&gt;
&lt;li&gt;Wednesday 5/29: RTM of HttpClient 2.1. Yep, it&amp;rsquo;s only a week away now, but it entirely depends on your feedback. If we find substantial issues, we might change the release date.&lt;/li&gt;
&lt;li&gt;Mid-June: Beta of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;li&gt;End of June: RC of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;li&gt;Around July (depending on feedback): RTM of HttpClient 2.2 with automatic decompression&lt;/li&gt;
&lt;/ul&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;We released an RC version of the &lt;a href="http://nuget.org/packages/Microsoft.Net.Http/"&gt;Microsoft.Net.Http&lt;/a&gt; NuGet package. We expect this to be the last preview of HttpClient before we ship an RTM. Please provide feedback if you find any issues.&lt;/p&gt;
&lt;p&gt;Of course, we&amp;rsquo;d also love to hear from you if everything just works. After all, we're happy if you're happy!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10419964" width="1" height="1"&gt;</content><author><name>Immo Landwerth [MSFT]</name><uri>http://blogs.msdn.com/terrajobst_4000_web.de/ProfileUrlRedirect.ashx</uri></author><category term="bcl" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/bcl/" /><category term="portable class libraries" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/portable+class+libraries/" /><category term="nuget" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/nuget/" /></entry><entry><title>.NET Crash Dump and Live Process Inspection</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/05/01/net-crash-dump-and-live-process-inspection.aspx" /><link rel="enclosure" type="application/octet-stream" length="3602" href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-41-54-93/ClrMDSample_2E00_cs" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/05/01/net-crash-dump-and-live-process-inspection.aspx</id><published>2013-05-02T04:44:00Z</published><updated>2013-05-02T04:44:00Z</updated><content type="html">&lt;p&gt;&lt;em&gt;Analyzing crash dumps can be complicated. Although Visual Studio supports viewing managed crash dumps, you often have to resort to more specialized tools like the SOS debugging extensions or WinDbg. In today&amp;rsquo;s post, &lt;strong&gt;Lee Culver, software developer on the .NET Runtime team&lt;/strong&gt;, will introduce you to a new managed library that allows you to automate inspection tasks and access even more debugging information. --Immo&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Today are we excited to announce the beta release of the &lt;a href="https://nuget.org/packages/Microsoft.Diagnostics.Runtime"&gt;Microsoft.Diagnostics.Runtime component&lt;/a&gt; (called ClrMD for short) through the NuGet Package Manager.&lt;/p&gt;
&lt;p&gt;ClrMD is a set of advanced APIs for programmatically inspecting a crash dump of a .NET program much in the same way as the &lt;a href="http://msdn.microsoft.com/en-us/library/bb190764.aspx"&gt;SOS Debugging Extensions&lt;/a&gt; (SOS). It allows you to write automated crash analysis for your applications and automate many common debugger tasks.&lt;/p&gt;
&lt;p&gt;We understand that this API won&amp;rsquo;t be for everyone -- hopefully debugging .NET crash dumps is a rare thing for you. However, our .NET Runtime team has had so much success automating complex diagnostics tasks with this API that we wanted to release it publicly.&lt;/p&gt;
&lt;p&gt;One last, quick note, before we get started: The ClrMD managed library is a wrapper around CLR internal-only debugging APIs. Although those internal-only APIs are very useful for diagnostics, we do not support them as a public, documented release because they are incredibly difficult to use and tightly coupled with other implementation details of the CLR. ClrMD addresses this problem by providing an easy-to-use managed wrapper around these low-level debugging APIs.&lt;/p&gt;
&lt;h1&gt;Getting Started&lt;/h1&gt;
&lt;p&gt;Let's dive right into an example of what can be done with ClrMD. The API was designed to be as discoverable as possible, so IntelliSense will be your primary guide. As an initial example, we will show you how to collect a set of heap statistics (objects, sizes, and counts) similar to what SOS reports when you run the command &lt;strong&gt;!dumpheap &amp;ndash;stat&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The &amp;ldquo;root&amp;rdquo; object of ClrMD to start with is the &lt;strong&gt;DataTarget&lt;/strong&gt; class. A DataTarget represents either a crash dump or a live .NET process. In this example, we will attach to a live process that has the name &amp;ldquo;HelloWorld.exe&amp;rdquo; with a timeout of 5 seconds to attempt to attach:&lt;/p&gt;
&lt;pre&gt;        int pid = Process.GetProcessesByName("HelloWorld")[0].Id;
        using (DataTarget dataTarget = DataTarget.AttachToProcess(pid, 5000))
        {
            string dacLocation = dataTarget.ClrVersions[0].TryGetDacLocation();
            ClrRuntime runtime = dataTarget.CreateRuntime(dacLocation);

            // ...
        }    &lt;/pre&gt;
&lt;p&gt;You may wonder what the &lt;strong&gt;TryGetDacLocation&lt;/strong&gt; method does. The CLR is a managed runtime, which means that it provides additional abstractions, such as garbage collection and JIT compilation, over what the operating system provides. The bookkeeping for those abstractions is done via internal data structures that live within the process. Those data structures are specific to the CPU architecture and the CLR version. In order to decouple debuggers from the internal data structures, the CLR provides a data access component (DAC), implemented in mscordacwks.dll. The DAC has a standardized interface and is used by the debugger to obtain information about the state of those abstractions, for example, the managed heap. It is essential to use the DAC that matches the CLR version and the architecture of the process or crash dump you want to inspect. For a given CLR version, the &lt;strong&gt;TryGetDacLocation&lt;/strong&gt; method tries to find a matching DAC on the same machine. If you need to inspect a process for which you do not have a matching CLR installed, you have another option: you can copy the DAC from a machine that has that version of the CLR installed. In that case, you provide the path to the alternate mscordacwks.dll to the &lt;strong&gt;CreateRuntime&lt;/strong&gt; method manually. You can read more about the DAC &lt;a href="http://msdn.microsoft.com/en-us/library/windows/hardware/ff540665.aspx"&gt;on MSDN&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Note that the DAC is a native DLL and must be loaded into the program that uses ClrMD. If the dump or the live process is 32-bit, you must use the 32-bit version of the DAC, which, in turn, means that your inspection program needs to be 32-bit as well. The same is true for 64-bit processes. Make sure that your program&amp;rsquo;s platform matches what you are debugging.&lt;/p&gt;
&lt;h1&gt;Analyzing the Heap&lt;/h1&gt;
&lt;p&gt;Once you have attached to the process, you can use the &lt;strong&gt;runtime&lt;/strong&gt; object to inspect the contents of the GC heap:&lt;/p&gt;
&lt;pre&gt;        ClrHeap heap = runtime.GetHeap();
        foreach (ulong obj in heap.EnumerateObjects())
        {
            ClrType type = heap.GetObjectType(obj);
            ulong size = type.GetSize(obj);
            Console.WriteLine("{0,12:X} {1,8:n0} {2}", obj, size, type.Name);
        }
    &lt;/pre&gt;
&lt;p&gt;This produces output similar to the following:&lt;/p&gt;
&lt;pre&gt;         23B1D30       36 System.Security.PermissionSet
         23B1D54       20 Microsoft.Win32.SafeHandles.SafePEFileHandle
         23B1D68       32 System.Security.Policy.PEFileEvidenceFactory
         23B1D88       40 System.Security.Policy.Evidence
    &lt;/pre&gt;
&lt;p&gt;However, the original goal was to output a set of heap statistics. Using the data above, you can use a LINQ query to group the heap by type and sort by total object size:&lt;/p&gt;
&lt;pre&gt;        var stats = from o in heap.EnumerateObjects()
                    let t = heap.GetObjectType(o)
                    group o by t into g
                    let size = g.Sum(o =&amp;gt; (uint)g.Key.GetSize(o))
                    orderby size
                    select new
                    {
                        Name = g.Key.Name,
                        Size = size,
                        Count = g.Count()
                    };

        foreach (var item in stats)
            Console.WriteLine("{0,12:n0} {1,12:n0} {2}", item.Size, item.Count, item.Name);
    &lt;/pre&gt;
&lt;p&gt;This will output data like the following -- a collection of statistics about what objects are taking up the most space on the GC heap for your process:&lt;/p&gt;
&lt;pre&gt;           564           11 System.Int32[]
           616            2 System.Globalization.CultureData
           680           18 System.String[]
           728           26 System.RuntimeType
           790            7 System.Char[]
         5,788          165 System.String
        17,252            6 System.Object[]
    &lt;/pre&gt;
&lt;h1&gt;ClrMD Features and Functionality&lt;/h1&gt;
&lt;p&gt;Of course, there&amp;rsquo;s a lot more to this API than simply printing out heap statistics. You can also walk every managed thread in a process or crash dump and print out a managed callstack. For example, this code prints the managed stack trace for each thread, similar to what the SOS &lt;strong&gt;!clrstack&lt;/strong&gt; command would report (and similar to the output in the Visual Studio stack trace window):&lt;/p&gt;
&lt;pre&gt;        foreach (ClrThread thread in runtime.Threads)
        {
            Console.WriteLine("ThreadID: {0:X}", thread.OSThreadId);
            Console.WriteLine("Callstack:");

            foreach (ClrStackFrame frame in thread.StackTrace)
                Console.WriteLine("{0,12:X} {1,12:X} {2}", frame.InstructionPointer, frame.StackPointer, frame.DisplayString);

            Console.WriteLine();
        }
    &lt;/pre&gt;
&lt;p&gt;This produces output similar to the following:&lt;/p&gt;
&lt;pre&gt;        ThreadID: 2D90
        Callstack:
                   0       90F168 HelperMethodFrame
            660E3365       90F1DC System.Threading.Thread.Sleep(Int32)
              C70089       90F1E0 HelloWorld.Program.Main(System.String[])
                   0       90F36C GCFrame
    &lt;/pre&gt;
&lt;p&gt;Each &lt;strong&gt;ClrThread&lt;/strong&gt; object also contains a &lt;strong&gt;CurrentException&lt;/strong&gt; property, which may be null, but if not, contains the last thrown exception on this thread. This exception object contains the full stack trace, message, and type of the exception thrown.&lt;/p&gt;
&lt;p&gt;ClrMD also provides the following features:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Gets general information about the GC heap:
&lt;ul&gt;
&lt;li&gt;Whether the GC is workstation or server&lt;/li&gt;
&lt;li&gt;The number of logical GC heaps in the process&lt;/li&gt;
&lt;li&gt;Data about the bounds of GC segments&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Walks the CLR&amp;rsquo;s handle table (similar to &lt;strong&gt;!gchandles&lt;/strong&gt; in SOS).&lt;/li&gt;
&lt;li&gt;Walks the application domains in the process and identifies which modules are loaded into them.&lt;/li&gt;
&lt;li&gt;Enumerates threads, callstacks of those threads, the last thrown exception on threads, etc.&lt;/li&gt;
&lt;li&gt;Enumerates the object roots of the process (as the GC sees them for our mark-and-sweep algorithm).&lt;/li&gt;
&lt;li&gt;Walks the fields of objects.&lt;/li&gt;
&lt;li&gt;Gets data about the various heaps that the .NET runtime uses to see where memory is going in the process (see &lt;strong&gt;ClrRuntime.EnumerateMemoryRegions&lt;/strong&gt; in the ClrMD package).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;All of this functionality can generally be found on the &lt;strong&gt;ClrRuntime&lt;/strong&gt; or the &lt;strong&gt;ClrHeap&lt;/strong&gt; objects, as seen above. IntelliSense can help you explore the various properties and functions when you install the ClrMD package. In addition, you can also use the attached sample code.&lt;/p&gt;
&lt;p&gt;Please use the comments under this post to let us know if you have any feedback!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10415493" width="1" height="1"&gt;</content><author><name>Immo Landwerth [MSFT]</name><uri>http://blogs.msdn.com/terrajobst_4000_web.de/ProfileUrlRedirect.ashx</uri></author><category term="clr" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/clr/" /><category term="releases" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/releases/" /><category term="diagnostics" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/diagnostics/" /></entry><entry><title>Social Engineering</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/04/24/social-engineering.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/04/24/social-engineering.aspx</id><published>2013-04-24T18:36:00Z</published><updated>2013-04-24T18:36:00Z</updated><content type="html">&lt;p&gt;When people in our industry use the term &amp;ldquo;social engineering&amp;rdquo; they are usually referring to &lt;a href="http://en.wikipedia.org/wiki/Social_engineering_(security)"&gt;security attacks&lt;/a&gt;. Politicians and lobbyists &lt;a href="http://en.wikipedia.org/wiki/Social_engineering_(political_science)"&gt;would mean something entirely different&lt;/a&gt; too. But that&amp;rsquo;s not what I will talk about here. Instead, I&amp;rsquo;ll talk about the kind of social life we&amp;rsquo;ve around in our team.&lt;/p&gt;
&lt;p&gt;Why am I using the term engineering then? Because I strongly believe that building a great team is a conscious effort. &lt;a href="http://xkcd.com/978/"&gt;Wikipedia defines&lt;/a&gt; the term &lt;a href="http://en.wikipedia.org/wiki/Engineering"&gt;engineering&lt;/a&gt; as follows:&lt;/p&gt;
&lt;p style="margin-left: 40px;"&gt;&lt;em&gt;Engineering is the application of scientific, economic, social, and practical knowledge, in order to design, build, and maintain structures, machines, devices, systems, materials and processes.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;From my point of view, building great software is a lot easier if you have a great team. You obviously can&amp;rsquo;t build a great team by writing a spec and triaging bugs. But you nonetheless need to invest into it as it doesn&amp;rsquo;t come for free or even happen automatically.&lt;/p&gt;
&lt;p&gt;In this post, I&amp;rsquo;d like to show some of the big and small things that my team does and what makes working with this team so great &amp;ndash; even when being under stress.&lt;/p&gt;
&lt;h1&gt;Official: Morale Events&lt;/h1&gt;
&lt;p&gt;About twice a year each team at Microsoft has a morale event. It&amp;rsquo;s up to the team to decide what to do but it typically involves some kind of team sport and food. Usually, these events are paid for by Microsoft. But before you think Formula 1 and Champaign with caviar: like in almost every company budget for those type of things is limited. However, I don&amp;rsquo;t think a successful morale event needs a lot of money. All it needs is a point in time and a place to gather.&lt;/p&gt;
&lt;p&gt;About a month ago, our team went out to play &lt;a href="http://en.wikipedia.org/wiki/Kickball"&gt;kickball&lt;/a&gt; and have a BBQ in a public park. In case you wonder whether we had fun: you can judge by browsing the pictures below.&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;a href="http://sdrv.ms/12w388v"&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/1581.SocialEngineering1.jpg" alt="" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p style="text-align: center;"&gt;(Click picture or &lt;a href="http://sdrv.ms/12w388v"&gt;this link&lt;/a&gt;&amp;nbsp;to see more pictures)&lt;/p&gt;
&lt;h1&gt;Semi Official: Get Together&lt;/h1&gt;
&lt;p&gt;It would miss the point if I&amp;rsquo;d state that it&amp;rsquo;s only the employer&amp;rsquo;s responsibility to invest into team building. In fact, I&amp;rsquo;m not even sure building a team like that is possible. From personal experience I&amp;rsquo;d say that in all the teams I&amp;rsquo;ve worked in the ones with the best culture had one thing in common: most of the team building was driven by individual team members.&lt;/p&gt;
&lt;p&gt;In our team, we usually hang out during lunch time instead of using this time of the day to be productive in front of the computer. However, I don&amp;rsquo;t mean to say you absolutely have to have a team lunch. But in my experience talking to your coworkers in an unofficial environment, such as the company&amp;rsquo;s cafeteria or a sushi place, is super helpful. For one, you have a venue to talk about personal stuff, such as renovating your living room or the tough nights you had because your daughter is getting teeth. And secondly, chances are you talk about work stuff as well. I found that people are more open to make compromises when they talk about the issue in a relaxing environment. Also, I&amp;rsquo;ve found on more than one occasion we developed a brilliant idea during lunch.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://www.joelonsoftware.com/items/2011/04/28.html"&gt;Joel takes this one step further&lt;/a&gt; and has lunch delivered to his employees so that they can all sit together as one big family.&lt;/p&gt;
&lt;p&gt;&lt;img style="margin-right: auto; margin-left: auto; display: block;" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/7853.SocialEngineering2.jpg" alt="" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;In addition to that, we meet every Friday after work in a social area in our building. Each week, someone else is responsible for getting the beer, chips and cake. Yes, &lt;a href="http://en.wikipedia.org/wiki/Portal_(video_game)"&gt;there will be cake&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;Unofficial: Office Pranks&lt;/h1&gt;
&lt;p&gt;At Microsoft, we have a long tradition of office pranks. They range from smaller jokes like removing the computer equipment to more elaborate pranks like replacing the door with a fully painted dry-wall. Needless to say they are unofficial and not driven by Microsoft, but completely organized by individual team members.&lt;/p&gt;
&lt;p&gt;When I went on a conference trip to Germany a few weeks ago, my team pulled off a super awesome office prank. Since I&amp;rsquo;m a big Star Trek fan they got inspired by &lt;a href="http://www.youtube.com/watch?v=rQ6LC-olw9Q"&gt;this episode&lt;/a&gt; and flooded my office with &lt;a href="http://en.wikipedia.org/wiki/Tribble_(Star_Trek)"&gt;tribbles&lt;/a&gt;. Great pictures and epic making-of mails can be found below.&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;a href="http://sdrv.ms/XNzgow"&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34/7444.SocialEngineering3.jpg" alt="" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p style="text-align: center;"&gt;(Click picture or &lt;a href="http://sdrv.ms/XNzgow"&gt;this link&lt;/a&gt;&amp;nbsp;to see more pictures)&lt;/p&gt;
&lt;p&gt;Special thanks to our release PM Marc Goodner who organized and PM&amp;rsquo;ed this epic prank!&lt;/p&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;In case you didn&amp;rsquo;t notice, I wrote this post primarily to say Thanks to my team. We talk a lot about the software we ship but cool stuff deserves to be shared &amp;ndash; even it&amp;rsquo;s not shipping and especially when it involves people.&lt;/p&gt;
&lt;p&gt;In case you thought &amp;ldquo;I wish I could be part of such a team&amp;rdquo; I&amp;rsquo;ve good news for you. &lt;a href="http://aka.ms/f1jurj"&gt;We are hiring!&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As always, we love to hear what you have to say. What do you do to keep up the team spirit? Share your story in the comments!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10413741" width="1" height="1"&gt;</content><author><name>Immo Landwerth [MSFT]</name><uri>http://blogs.msdn.com/terrajobst_4000_web.de/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>.NET Memory Allocation Profiling with Visual Studio 2012</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/04/04/net-memory-allocation-profiling-with-visual-studio-2012.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/04/04/net-memory-allocation-profiling-with-visual-studio-2012.aspx</id><published>2013-04-04T15:54:00Z</published><updated>2013-04-04T15:54:00Z</updated><content type="html">&lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;This post was written by Stephen Toub, a frequent contributor to the &lt;a href="http://blogs.msdn.com/b/pfxteam"&gt;Parallel Programming in .NET blog&lt;/a&gt;. He shows us how Visual Studio 2012 and an attention to detail can help you discover unnecessary allocations in your app that can prevent it from achieving higher performance. &lt;/em&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Visual Studio 2012 has a wealth of valuable functionality, so much so that I periodically hear developers that already use Visual Studio asking for a feature the IDE already has and that they’ve just never discovered. Other times, I hear developers asking about a specific feature, thinking it’s meant for one purpose, not realizing it’s really intended for another.&lt;/p&gt;  &lt;p&gt;Both of these cases apply to Visual Studio’s &lt;a href="http://msdn.microsoft.com/library/dd264966.aspx"&gt;.NET memory allocation profiler&lt;/a&gt;. Many developers that could benefit from it don’t know it exists, and other developers have an incorrect expectation for its purpose. This is unfortunate, as the feature can provide a lot of value for particular scenarios; many developers will benefit from understanding first that it exists, and second the intended scenarios for its use.&lt;/p&gt;  &lt;h3&gt;Why memory profiling?&lt;/h3&gt;  &lt;p&gt;When it comes to .NET and memory analysis, there are two primary reasons one would want to use a diagnostics tool:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;b&gt;To discover memory leaks. &lt;/b&gt;Leaks on a garbage-collecting runtime like the CLR manifest differently than do leaks in a non-garbage-collected environment, such as in code written in C/C++. A leak in the latter typically occurs due to the developer not manually freeing some memory that was previously allocated. In a garbage collected environment, however, manually freeing memory isn’t required, as that’s the duty of the &lt;a href="http://msdn.microsoft.com/library/0xy59wtx.aspx"&gt;garbage collector&lt;/a&gt; (GC). However, the GC can only release memory that is provably no longer being used, meaning as long as there are no rooted references to the memory. Leaks in .NET code manifest then when some memory that should have been collected is incorrectly still rooted, e.g. a reference to the object occurs in an event handler registered with a static event. A good memory analysis tool might help you to find such leaks, such as by allowing you to take snapshots of the process at two different points and then comparing those snapshots to see which objects stuck around for the second point, and more importantly, why.&lt;/li&gt;    &lt;li&gt;&lt;b&gt;To discover unnecessary allocations.&lt;/b&gt; In .NET, allocation is often quite cheap. This cost is deceptive, however, as there are more costs later when the GC needs to clean up. The more memory that gets allocated, the more frequently the GC will need to run, and typically the more objects that survive collections, the more work the GC needs to do when it runs to determine which objects are no longer reachable. Thus, the more allocations a program does, the higher the GC costs will be. These GC costs are often negligible to the program’s performance profile, but for certain kinds of apps, especially those on servers that require high-throughput operation, these costs can add up quickly and make a noticeable impact to the performance of the app. As such, a good memory analysis tool might help you to understand all of the allocation being done by the program, in order to help spot allocations you can potentially avoid.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The .NET memory profiler included in Visual Studio 2012 (Professional and higher versions) was designed primarily to address the latter case of helping to discover unnecessary allocations, and it’s quite useful towards that goal, as the rest of this post will explore. The tool is not tuned for the former case of finding and fixing memory leaks, though this is an area the Visual Studio diagnostics team is looking to address in depth for the future (you can see &lt;a href="http://msdn.microsoft.com/library/windows/apps/jj819176.aspx"&gt;such an experience for JavaScript&lt;/a&gt; that was added to Visual Studio as part of &lt;a href="http://blogs.msdn.com/b/somasegar/archive/2012/11/26/visual-studio-2012-update-1-now-available.aspx"&gt;VS2012.1&lt;/a&gt;). While the tool today does have an &lt;a href="http://msdn.microsoft.com/library/dd264934.aspx"&gt;advanced option to track when objects are collected&lt;/a&gt;, it doesn’t help you to understand why objects weren’t collected or why they were held onto longer than was expected.&lt;/p&gt;  &lt;p&gt;There are also other useful tools in this space. The downloadable &lt;a href="http://www.microsoft.com/download/details.aspx?id=28567"&gt;PerfView&lt;/a&gt; &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/10/09/improving-your-app-s-performance-with-perfview.aspx"&gt;tool&lt;/a&gt; doesn’t provide as user-friendly an interface as does the .NET memory profiler in Visual Studio 2012, but it is a very powerful tool that supports both tasks of finding memory leaks and discovering unnecessary allocations. It also supports profiling Windows Store apps, which the .NET memory allocation profiler in Visual Studio 2012 does not currently support as of the writing of this post.&lt;/p&gt;  &lt;h3&gt;Example to be optimized&lt;/h3&gt;  &lt;p&gt;To better understand the memory profiler’s role and how it can help, let’s walk through an example. We’ll start with the core method that we’ll be looking to optimize (in a real-world case, you’d likely be analyzing your whole application and narrowing in on the particular offending areas, but for the purpose of this example, we’ll keep this constrained):&lt;/p&gt;  &lt;div id="codeSnippetWrapper"&gt;   &lt;blockquote&gt;     &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; async Task&amp;lt;T&amp;gt; WithCancellation1&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; Task&amp;lt;T&amp;gt; task, CancellationToken cancellationToken)
{
    var tcs = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;&lt;span class="kwrd"&gt;bool&lt;/span&gt;&amp;gt;();
    &lt;span class="kwrd"&gt;using&lt;/span&gt; (cancellationToken.Register(() =&amp;gt; tcs.TrySetResult(&lt;span class="kwrd"&gt;true&lt;/span&gt;)))
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (task != await Task.WhenAny(task, tcs.Task))
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; OperationCanceledException(cancellationToken);
    &lt;span class="kwrd"&gt;return&lt;/span&gt; await task;
}&lt;/pre&gt;
  &lt;/blockquote&gt;
  &lt;/div&gt;

&lt;p&gt;The purpose of this small method is to enable code to await a task in a cancelable manner, meaning that regardless of whether the task has completed, the developer wants to be able to stop waiting for it. Instead of writing code like:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="csharpcode"&gt;T result = await someTask;&lt;/pre&gt;
&lt;/blockquote&gt;


&lt;p&gt;the developer would write:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="csharpcode"&gt;T result = await someTask.WithCancellation1(token);&lt;/pre&gt;
&lt;/blockquote&gt;


&lt;p&gt;and if cancellation is requested on the relevant CancellationToken before the task completes, an OperationCanceledException will be thrown. This is achieved in WithCancellation1 by wrapping the original task in an async method. The method creates a second task that will complete when cancellation is requested (by Registering a call to TrySetResult with the CancellationToken), and then uses Task.WhenAny to wait for either the original task or the cancellation task to complete. As soon as either does, the async method completes, either by throwing a cancellation exception if the cancellation task completed first, or by propagating the outcome of the original task by awaiting it. (For more details, see the blog post “&lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx"&gt;How do I cancel non-cancelable async operations?&lt;/a&gt;”)&lt;/p&gt;

&lt;p&gt;To understand the allocations involved in this method, we’ll use a small harness method:&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="csharpcode"&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Threading;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Threading.Tasks;
 
&lt;span class="kwrd"&gt;class&lt;/span&gt; Harness
{
    &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main() 
     { 
         Console.ReadLine(); &lt;span class="rem"&gt;// wait until profiler attaches&lt;/span&gt;
         TestAsync().Wait(); 
     }
    &lt;span class="kwrd"&gt;static&lt;/span&gt; async Task TestAsync()
    {
        var token = CancellationToken.None;
        &lt;span class="kwrd"&gt;for&lt;/span&gt;(&lt;span class="kwrd"&gt;int&lt;/span&gt; i=0; i&amp;lt;100000; i++)
            await Task.FromResult(42).WithCancellation1(token);
    }
}
 

&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Extensions
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; async Task&amp;lt;T&amp;gt; WithCancellation1&amp;lt;T&amp;gt;(
    &lt;span class="kwrd"&gt;this&lt;/span&gt; Task&amp;lt;T&amp;gt; task, CancellationToken cancellationToken)
    {
        var tcs = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;&lt;span class="kwrd"&gt;bool&lt;/span&gt;&amp;gt;();
        &lt;span class="kwrd"&gt;using&lt;/span&gt; (cancellationToken.Register(() =&amp;gt; tcs.TrySetResult(&lt;span class="kwrd"&gt;true&lt;/span&gt;)))
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (task != await Task.WhenAny(task, tcs.Task))
                &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; OperationCanceledException(cancellationToken);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; await task;
    }
}&lt;/pre&gt; 
  &lt;/pre&gt;
&lt;/blockquote&gt;


&lt;p&gt;The TestAsync method will iterate 100,000 times. Each time, it creates a new task, invokes the WithCancellation1 on it, and awaits the result of that WithCancellation1 call. This await will complete synchronously, as the task created by Task.FromResult is returned in an already completed state, and the WithCancellation1 method itself doesn’t introduce any additional asynchrony such that the task it returns will complete synchronously as well.&lt;/p&gt;

&lt;h3&gt;Running the .NET memory allocation profiler&lt;/h3&gt;

&lt;p&gt;To start the memory allocation profiler, in Visual Studio go to the Analyze menu and select “Launch Performance Wizard…”. This will open a dialog like the following:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/1586.image_5F00_6BAB9C20.png" width="487" height="419" /&gt;&lt;/p&gt;

&lt;p&gt;Choose “.NET memory allocation (sampling)”, click Next twice, followed by Finish (if this is the first time you’ve used the profiler since you logged into Windows, you’ll need to accept the elevation prompt so the profiler can start). At that point, the application will be launched and the profiler will start monitoring it for allocations (the harness code above also requires that you press ‘Enter’, in order to ensure the profiler has attached by the time the program starts the real test). When the app completes, or when you manually choose to stop profiling, the profiler will load symbols and will start analyzing the trace. That’s a good time to go and get yourself a cup of coffee, or lunch, as depending on how many allocations occurred, the tool can take a while to do this analysis.&lt;/p&gt;

&lt;p&gt;When the analysis completes, we’re presented with a summary of the allocations that occurred, including highlighting the functions that allocated the most memory, the types that resulted in the most memory allocated, and the types with the most instances allocated:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/7652.image_5F00_1D3709B6.png" width="624" height="334" /&gt;&lt;/p&gt;

&lt;p&gt;From there, we can drill in further, by looking at the allocations summary (choose “Allocation” from the “Current View” dropdown):&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/5518.image_5F00_120D7F6C.png" width="624" height="205" /&gt;&lt;/p&gt;

&lt;p&gt;Here, we get to see a row for each type that was allocated, with the columns showing information about how many allocations were tracked, how much space was associated with those allocations, and what percentage of allocations mapped back to that type. We can also expand an entry to see the stack of method calls that resulted in these allocations:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/2465.image_5F00_71F272AE.png" width="624" height="279" /&gt;&lt;/p&gt;

&lt;p&gt;By selecting the “Functions” view, we can get a different pivot on this data, highlighting which functions allocated the most objects and bytes:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/3036.image_5F00_3CE5E37E.png" width="624" height="212" /&gt;&lt;/p&gt;

&lt;h3&gt;Interpreting and acting on the profiling results&lt;/h3&gt;

&lt;p&gt;With this capability, we can analyze our example’s results. First, we can see that there’s a substantial number of allocations here, which might be surprising. After all, in our example we were using WithCancellation1 with a task that was already completed, which means there should have been very little work to do (with the task already done, there is nothing to cancel), and yet from the above trace we can see that each iteration of our example is resulting in:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Three allocations of Task`1 (we ran the harness 100K times and can see there were ~300K allocations)&lt;/li&gt;
&lt;/ul&gt;

&lt;ul&gt;
  &lt;li&gt;Two allocations of Task[] &lt;/li&gt;
&lt;/ul&gt;

&lt;ul&gt;
  &lt;li&gt;One allocation each of TaskCompletionSource`1, Action, a compiler-generated type called &amp;lt;&amp;gt;c_DisplayClass2`1, and some type called CompleteOnInvokePromise&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That’s nine allocations for a case where we might expect only one (the task allocation we explicitly asked for in the harness by calling Task.FromResult), with our WithCancellation1 method incurring eight allocations.&lt;/p&gt;

&lt;p&gt;For helper operations on tasks, it’s actually fairly common to deal with already completed tasks, as often times operations implemented to be asynchronous will actually complete synchronously (e.g. one read operation on a network stream may buffer into memory enough additional data to fulfill a subsequent read operation). As such, optimizing for the already completed case can be really beneficial for performance. Let’s try. Here’s a second attempt at WithCancellation, one that optimizes for several “already completed” cases:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; Task&amp;lt;T&amp;gt; WithCancellation2&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; Task&amp;lt;T&amp;gt; task, &lt;br /&gt;                             CancellationToken cancellationToken)
    {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (task.IsCompleted || !cancellationToken.CanBeCanceled)
            &lt;span class="kwrd"&gt;return&lt;/span&gt; task;
        &lt;span class="kwrd"&gt;else&lt;/span&gt; &lt;span class="kwrd"&gt;if&lt;/span&gt; (cancellationToken.IsCancellationRequested)
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; Task&amp;lt;T&amp;gt;(() =&amp;gt; &lt;span class="kwrd"&gt;default&lt;/span&gt;(T), cancellationToken);
        &lt;span class="kwrd"&gt;else&lt;/span&gt;
            &lt;span class="kwrd"&gt;return&lt;/span&gt; task.WithCancellation1(cancellationToken);
    }&lt;/pre&gt;


&lt;p&gt;This implementation checks:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;First, whether the task is already completed or whether the supplied CancellationToken can’t be canceled; in both of those cases, there’s no additional work needed, as cancellation can’t be applied, and as such we can just return the original task immediately rather than spending any time or memory creating a new one.&lt;/li&gt;
&lt;/ul&gt;

&lt;ul&gt;
  &lt;li&gt;Then whether cancellation has already been requested; if it has, we can allocate a single already-canceled task to be returned, rather than spending the eight allocations we previously paid to invoke our original implementation.&lt;/li&gt;
&lt;/ul&gt;

&lt;ul&gt;
  &lt;li&gt;Finally, if none of these fast paths apply, we fall through to calling the original implementation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Re-profiling our micro-benchmark while using WithCancellation2 instead of WithCancellation1 provides a much improved outlook (you’ll likely notice that the analysis completes much more quickly than it did before, already a sign that we’ve significantly decreased memory allocation). Now we have just have the primary allocation we expected, the one from Task.FromResult called from our TestAsync method in the harness:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/7268.image_5F00_1CCAD6C1.png" width="624" height="115" /&gt;&lt;/p&gt;

&lt;p&gt;So, we’ve now successfully optimized the case where the task is already completed, where cancellation can’t be requested, or where cancellation has already been requested. What about the case where we do actually need to invoke the more complicated logic? Are there any improvements that can be made there?&lt;/p&gt;

&lt;p&gt;Let’s change our benchmark to use a task that’s not already completed by the time we invoke WithCancellation2, and also to use a token that can have cancellation requested. This will ensure we make it to the “slow” path:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;static&lt;/span&gt; async Task TestAsync()
    {
        var token = &lt;span class="kwrd"&gt;new&lt;/span&gt; CancellationTokenSource().Token;
        &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; 100000; i++)
        {
            var tcs = &lt;span class="kwrd"&gt;new&lt;/span&gt; TaskCompletionSource&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
            var t = tcs.Task.WithCancellation2(token);
            tcs.SetResult(42);
            await t;
        }
    }&lt;/pre&gt;


&lt;p&gt;Profiling again provides more insight:&lt;/p&gt;

&lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/0486.image_5F00_7CAFCA03.png" width="624" height="132" /&gt;&lt;/p&gt;

&lt;p&gt;On this slow path, there are now 14 total allocations per iteration, including the 2 from our TestAsync harness (the TaskCompletionSource&amp;lt;int&amp;gt; we explicitly create, and the Task&amp;lt;int&amp;gt; it creates). At this point, we can use all of the information provided by the profiling results to understand where the remaining 12 allocations are coming from and to then address them as is relevant and possible. For example, let’s look at two allocations specifically: the &amp;lt;&amp;gt;c__DisplayClass2`1 instance and one of the two Action instances. These two allocations will likely be logical to anyone familiar with &lt;a href="http://blogs.msdn.com/b/pfxteam/archive/2012/02/29/10263921.aspx"&gt;how the C# compiler handles closures&lt;/a&gt;. Why do we have a closure? Because of this line:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt;(cancellationToken.Register(() =&amp;gt; tcs.TrySetResult(&lt;span class="kwrd"&gt;true&lt;/span&gt;)))&lt;/pre&gt;
&lt;/blockquote&gt;


&lt;p&gt;The call to Register is closing over the ‘tcs’ variable. But this isn’t strictly necessary: the Register method has another overload which instead of taking an Action takes an Action&amp;lt;object&amp;gt; and the object state to be passed to it. If we instead rewrite this line to use that state-based overload, along with a manually cached delegate, we can avoid the closure and those two allocations:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; Action&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt; s_cancellationRegistration =
    s =&amp;gt; ((TaskCompletionSource&amp;lt;&lt;span class="kwrd"&gt;bool&lt;/span&gt;&amp;gt;)s).TrySetResult(&lt;span class="kwrd"&gt;true&lt;/span&gt;);
…
&lt;span class="kwrd"&gt;using&lt;/span&gt;(cancellationToken.Register(s_cancellationRegistration, tcs))
  &lt;/pre&gt;
  &lt;/blockquote&gt;

&lt;p&gt;Rerunning the profiler confirms those two allocations are no longer occurring:&lt;/p&gt;

&lt;h3&gt;Start profiling today!&lt;/h3&gt;

&lt;p&gt;This cycle of profiling, finding and eliminating hotspots, and then going around again is a common approach towards improving the performance of your code, whether using a CPU profiler or a memory profiler. So, if you find yourself in a scenario where you determine that minimizing allocations is important for the performance of your code, give the .NET memory allocation profiler in Visual Studio 2012 a try. Feel free to &lt;a href="http://aka.ms/wpv10c"&gt;download the sample project used in this blog post&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;For more on profiling, see the blog of the &lt;a href="http://blogs.msdn.com/b/visualstudioalm/archive/tags/diagnostics/"&gt;Visual Studio Diagnostics team&lt;/a&gt;, and ask them questions in the &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/vsdebug/threads"&gt;Visual Studio Diagnostics forum&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Stephen Toub&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Follow us on Twitter (&lt;a href="https://twitter.com/dotnet"&gt;@dotnet&lt;/a&gt;) and Facebook (&lt;a href="http://facebook.com/dotnet"&gt;dotnet&lt;/a&gt;). You can follow other .NET teams, too: &lt;a href="http://twitter.com/aspnet"&gt;@aspnet&lt;/a&gt;/&lt;a href="http://facebook.com/asp.net"&gt;asp.net&lt;/a&gt;, &lt;a href="https://twitter.com/efmagicunicorns"&gt;@efmagicunicorns&lt;/a&gt;/&lt;a href="https://www.facebook.com/efmagicunicorns"&gt;efmagicunicorns&lt;/a&gt;, &lt;a href="http://twitter.com/visualstudio"&gt;@visualstudio&lt;/a&gt;/&lt;a href="https://www.facebook.com/visualstudio"&gt;visualstudio&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10407439" width="1" height="1"&gt;</content><author><name>The .NET Team</name><uri>http://blogs.msdn.com/dotnetteam_4000_outlook.com/ProfileUrlRedirect.ashx</uri></author><category term=".net framework" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/-net+framework/" /><category term="async" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/async/" /><category term="diagnostics" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/diagnostics/" /><category term="visual studio" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/visual+studio/" /></entry><entry><title>.NET Framework Documentation Improvements</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/02/19/net-documentation-improvements.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/02/19/net-documentation-improvements.aspx</id><published>2013-02-19T20:07:49Z</published><updated>2013-02-19T20:07:49Z</updated><content type="html">&lt;p&gt;The CLR documentation team has been busy responding to feedback and making updates and changes to the &lt;a href="http://msdn.microsoft.com/library/vstudio/w0x726c2.aspx"&gt;.NET Framework documentation&lt;/a&gt; in the MSDN Library. We would like to tell you about the most recent set of document updates, which were published earlier in February.&lt;/p&gt;  &lt;h3&gt;&lt;b&gt;Performance content&lt;/b&gt;&lt;/h3&gt;  &lt;p&gt;We have received extensive customer feedback regarding the importance of performance in .NET Framework apps, and we wanted to make it easier for you to find relevant content. &lt;/p&gt;  &lt;p&gt;As a result, we’ve reworked the existing performance and reliability topic to include more performance guidance as well as links to performance analysis tools and technology-specific performance content. We’ll continue to improve this documentation area in the coming months.&lt;/p&gt;  &lt;p&gt;Do take a look at the revised &lt;a href="http://msdn.microsoft.com/en-us/library/hh156536.aspx"&gt;Performance in .NET Framework Apps&lt;/a&gt; topic. Please give us your feedback to help us choose which area to focus on next. &lt;/p&gt;  &lt;h3&gt;&lt;b&gt;Overload list topics&lt;/b&gt;&lt;/h3&gt;  &lt;p&gt;We are experimenting with a new approach to document methods that have overloads. These pages have been an area of consistent feedback. We have heard that the current approach requires too many clicks to get to the overload page that you want. We are piloting this new approach with the following method overload pages:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx"&gt;DateTime.Parse&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/as4h66hd.aspx"&gt;Math.Round&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.string.string.aspx"&gt;String constructors&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/xh1dzhdx.aspx"&gt;String.Format&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Let’s take a look at why we decided to try something different with these pages. In the MSDN Library, our current documentation design for overloaded methods and constructors uses an overload list to provide summary information and links to individual overload pages. Typically, these pages include just the overload list, requiring you to choose one of the overloads to find any technical information for that method beyond just the overload signatures. For example, the following image shows a portion of the &lt;a href="http://msdn.microsoft.com/en-us/library/2se42k1z(v=vs.110).aspx"&gt;&lt;b&gt;String.Compare&lt;/b&gt;&lt;/a&gt; page. &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/7624.image_5F00_3FE79849.png" width="622" height="443" /&gt;&lt;/p&gt;  &lt;br /&gt;The overload list provides an abbreviated syntax for each overload (without its return value or parameter names) and a brief, typically one-sentence description. The page was designed to provide just enough information for you to select an overload, and then follow a link to detailed documentation about that overload. However, we have heard many of you ask for more detail on the overload page, such as individual parameters, return value information, and examples.   &lt;p&gt;Until now, our strategy has been to direct you to the detailed information on the individual overload pages. We had done two things to achieve that goal:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Added the following note before the overload list: &amp;quot;This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.&amp;quot; &lt;/li&gt;    &lt;li&gt;Reduced the visibility of these pages by ensuring that they do not appear in searches and member lists. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;However, even after those changes, we were still hearing requests for more information. To address this issue, we would like to solicit your feedback about the new approach we're trying out. As already stated, we've revised four overload list topics to provide complete documentation for all the individual method overloads. In each case, the overload list topic should serve as a one-stop source for information about that method and all its overloads. &lt;/p&gt;  &lt;p&gt;Note, though, that our build system does not yet support this revised format. Because of this, the boilerplate text &amp;quot;This method is overloaded…&amp;quot; continues to appear on these overload list pages. At a later time, we will remove that text.&lt;/p&gt;  &lt;p&gt;The expanded documentation is in the Remarks section and includes complete method syntax, parameter and return value descriptions, a list of exceptions, a table to help choose an overload, extended discussion of using the method, and at least one example for each overload.&amp;#160; Here are a few screenshots from the updated &lt;a href="http://msdn.microsoft.com/library/xh1dzhdx.aspx"&gt;String.Format&lt;/a&gt; overload page to give you a better idea of the information that you can expect on overload pages with this new approach. Feel free to check out the whole page for yourself.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/8475.image_5F00_5DC50CF1.png" width="519" height="480" /&gt;&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/0045.image_5F00_64781674.png" width="582" height="480" /&gt;&lt;/p&gt;  &lt;p&gt;&lt;img title="image" style="border: 0px currentcolor; margin-right: auto; margin-left: auto; float: none; display: block; background-image: none;" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-34-metablogapi/0068.image_5F00_445D09B7.png" width="498" height="480" /&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Tell us what you think of this approach. Does it make it easier to get to the information you need? Do you have any suggestions for further improvements? We look forward to hearing from you.&lt;/p&gt;  &lt;p&gt;Follow us on Twitter (&lt;a href="https://twitter.com/dotnet"&gt;@dotnet&lt;/a&gt;) and Facebook (&lt;a href="http://facebook.com/dotnet"&gt;dotnet&lt;/a&gt;). You can follow other .NET teams, too: &lt;a href="http://twitter.com/aspnet"&gt;@aspnet&lt;/a&gt;/&lt;a href="http://facebook.com/asp.net"&gt;asp.net&lt;/a&gt;, &lt;a href="https://twitter.com/efmagicunicorns"&gt;@efmagicunicorns&lt;/a&gt;/&lt;a href="https://www.facebook.com/efmagicunicorns"&gt;efmagicunicorns&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10395322" width="1" height="1"&gt;</content><author><name>Brandon Bray</name><uri>http://blogs.msdn.com/brb9_4000_cornell.edu/ProfileUrlRedirect.ashx</uri></author><category term="clr" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/clr/" /><category term=".net framework" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/-net+framework/" /><category term="performance" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/performance/" /><category term="bcl" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/bcl/" /><category term="announcement" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/announcement/" /><category term="docs" scheme="http://blogs.msdn.com/b/dotnet/archive/tags/docs/" /></entry><entry><title>C# is the “Language of the Year”</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dotnet/archive/2013/01/03/c-is-the-language-of-the-year.aspx" /><id>http://blogs.msdn.com/b/dotnet/archive/2013/01/03/c-is-the-language-of-the-year.aspx</id><published>2013-01-04T01:25:09Z</published><updated>2013-01-04T01:25:09Z</updated><content type="html">&lt;p&gt;It’s a great way to start a new year: the &lt;a href="https://sites.google.com/site/pydatalog/pypl/PyPL-PopularitY-of-Programming-Language"&gt;PYPL index has named C# the language of the year&lt;/a&gt;. This index focuses on the leading indicator of learning a language. It’s nice to see that there’s been increased interest in C# over the past year. In the spirit of learning something new, here’s what we suggest you check out if you’re looking to learn a new C# trick.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;b&gt;Learn to program with Async. &lt;/b&gt;Async is finally unleashing the power of multicore hardware. Where I/O is involved, we expect almost all new platform APIs to be exposed as async versions. This &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/04/03/async-in-4-5-worth-the-await.aspx"&gt;new language capability&lt;/a&gt; ensures that you can quickly build &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/11/13/the-net-framework-4-5-is-optimized-for-the-cloud.aspx"&gt;highly scalable&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx"&gt;highly responsive&lt;/a&gt; apps for the cloud and devices.       &lt;br /&gt;&lt;b&gt;       &lt;br /&gt;&lt;/b&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;Learn to build a Windows Store App.&lt;/b&gt; All of our favorite Windows Store apps were written with C# – &lt;a href="http://www.amazon.com/Windows-Apps-XAML-Unleashed-Nathan/dp/0672336014"&gt;yours can be too&lt;/a&gt;. Many of the new Windows APIs are &lt;a href="http://msdn.microsoft.com/en-us/magazine/jj651569.aspx"&gt;based on WinRT&lt;/a&gt;, which means that all of these new APIs are amazing with C#. To top it off, you can use &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/11/20/building-windows-store-apps-with-net.aspx"&gt;XAML&lt;/a&gt; or &lt;a href="http://sharpdx.org/"&gt;DirectX&lt;/a&gt;.       &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;Learn to build (or use) cross-platform libraries.&lt;/b&gt; .NET is now integral to every platform Microsoft builds. And with so many platforms to target, we’ve made it &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/07/06/targeting-multiple-platforms-with-portable-code-overview.aspx"&gt;easy to write portable libraries&lt;/a&gt; so you can distribute your binary once for all of them. Many of these libraries are available on &lt;a href="http://www.nuget.org/packages"&gt;NuGet&lt;/a&gt; such as &lt;a href="http://www.nuget.org/packages/Newtonsoft.Json"&gt;Json.NET&lt;/a&gt;. Not to mention that your C# code also works on billions of non-Microsoft devices thanks to &lt;a href="http://xamarin.com/"&gt;tools from Xamarin&lt;/a&gt;.       &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;Learn about the performance advantages of .NET.&lt;/b&gt; One of the best aspects of programming with C# is that your apps get faster by just upgrading to the latest version of Windows or .NET Framework. With Windows Server 2012, Windows 8 and .NET Framework 4.5 your app can see significant improvements in &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/07/20/the-net-framework-4-5-includes-new-garbage-collector-enhancements-for-client-and-server-apps.aspx"&gt;garbage collection&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/10/18/an-easy-solution-for-improving-app-launch-performance.aspx"&gt;startup time&lt;/a&gt;. &lt;a href="http://blogs.technet.com/b/windowsserver/archive/2012/06/07/bing-com-runs-on-windows-server-2012.aspx"&gt;Bing saw some amazing performance wins&lt;/a&gt; from .NET too.       &lt;br /&gt;      &lt;br /&gt;&lt;/li&gt;    &lt;li&gt;&lt;b&gt;Learn about cool libraries that build on top of C#.&lt;/b&gt; What makes C# so cool is that our innovations in the language have inspired new programming patterns and libraries. LINQ is awesome and it’s led to the &lt;a href="http://msdn.microsoft.com/en-us/data/gg577609.aspx"&gt;Reactive Extensions (Rx)&lt;/a&gt;. Just spend some time understanding how to use Rx and you’ll take your programming game to a new level.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;What new C# skill would you recommend everyone learn? Share your thoughts in the comments.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10382254" width="1" height="1"&gt;</content><author><name>Brandon Bray</name><uri>http://blogs.msdn.com/brb9_4000_cornell.edu/ProfileUrlRedirect.ashx</uri></author></entry></feed>