Friday, September 28, 2012

WCF Data Service: Error processing request stream. The property name Discount specified for type Order is not valid.

For a project we are using  a WCF Data Service. By using “Add service reference” we generated all the classes and a context on the client side. To simplify the usage of these classes, we want to extend some of them with some extra properties, e.g:
public partial class Order
{ 
 public int Discount
 { 
     get 
     { 
         return CalculateDiscount();
     } 
 } 
} 
After setting this up, we couldn’t no longer send updates to the server, instead we always got the following error message back:  "Error processing request stream. The property name 'Discount' specified for type 'Order' is not valid."
How can we tell WCF Data Service to ignore this property?
On the server side, doing this is easy. There is an IgnoreProperties attribute class that you can use to control the visibility of a property in a WCF DataService class. But this one is meant to be used on the server side not the client side.

But with some extra code, you can get the same thing done on the client side. Create a partial class for the Context and add the following:

partial void OnContextCreated() 
{ 
 this.WritingEntity += OnWritingEntity; 
} 
 
private void OnWritingEntity(object sender, System.Data.Services.Client.ReadingWritingEntityEventArgs e) 
{  
 foreach (XElement node in e.Data.Elements()) 
 { 
  if (node != null && node.Name.LocalName == "content") 
  { 
   foreach (XElement el in node.Elements()) 
   { 
    if (el.Name.LocalName == "properties") 
    { 
     foreach (XElement prop in el.Elements()) 
     { 
      if(prop.Name.LocalName=="Discount") 
      { 
       prop.Remove(); 
      } 
     } 
    } 
   } 
  } 
 } 
} 


 

Thursday, September 27, 2012

2 useful tools for the TFS administrator: TFS Power Tools 2012 & TFS Team Project Manager

Looking for some tools to simplify your job as a TFS administrator? These are 2 of the ‘must have’ tools:

Microsoft Visual Studio Team Foundation Server 2012 Power Tools

This is the latest update of the TFS Power Tools with support for Microsoft Visual Studio Team Foundation Server 2012.

Best Practices Analyzer

A diagnostic tool that you can use to perform the following actions:

  • Verify that the deployment for Team Foundation Server is configured according to recommended best practices
  • Identify the source of problems in an unhealthy deployment
  • Take a snapshot of the configuration of a deployment
  • Obtain usage data about the volume of data stored or accessed in the past 14 days. Includes specific information about database tables that have a tendency to grow and that may need to be reduced in size.
Process Template Editor

A Visual Studio 2012 add-in, located under the Tools menu, the Process Template Editor provides a graphical user interface for customizing Team Foundation Server process templates.

Storyboard Shapes

This tool enables you to create shapes for the PowerPoint storyboarding add-in with custom resize logic.

Team Explorer Enhancements

This tool provides additional Visual Studio menu options and functions to support finding files under version control by status or wildcard, opening a folder using File Explorer from the Source Control Explorer context menu, and labeling files and folders in Source Control Explorer. Clone builds definitions easily and copy work item paths. Collaborate and share with your teammates within Visual Studio using the new Team Members page in the Team Explorer tool window. You can communicate with your team through instant messaging, share queries and components, create workspace templates, and track your sprint progress.

Team Foundation Power Tool Command Line (tfpt.exe)

A companion tool to “tf.exe” that offers additional version control commands, work item tracking, and team project manipulation. Some commands invoke a graphical user interface when run.

Team Foundation Server Backups

You install this tool on the application-tier for Team Foundation Server. The tool can schedule backups for the following databases that your deployment of Team Foundation Server uses:

  • the configuration database
  • the database for each team project collection
  • the databases that Team Foundation Server uses in conjunction with SharePoint Products, if your deployment includes integration with SharePoint Products
  • the databases that Team Foundation Server uses in conjunction with SQL Server Reporting Services, if your deployment includes reports

By using the restore wizard included with this tool, you can restore your entire deployment to new hardware, or selectively restore team project collections to an earlier point in time.

Test Attachment Cleaner

The execution of a Test Run (whether automated or manual) generates a bunch of diagnostic data, which may be captured either automatically by the system or manually by the tester. This diagnostic data is critical in eliminating the “no repro” bug scenarios between the testers and developers. However, the downside of this rich diagnostic data captures is that the system/user generated diagnostic data, over a period of time, can grow at a rapid pace and start taking up database space.

In Visual Studio 2012, the database administrator has little or no control over what data gets attached as part of Test Runs. For example, she has no policy settings to limit the size of the data capture, or how long to hold the data before initiating a cleanup. This tool addresses these issues by:

  • Determining which set of diagnostic captures is taking up how much space AND
  • Reclaiming the space for runs which are no longer relevant from business perspective.
Windows PowerShell Cmdlets

This tool provides a Windows PowerShell interface that supports basic version control commands and a pipeline and glue to enable scripting.

Windows Shell Extensions

This tool provides integration with Windows Explorer and the common file dialogs. With this integration, you can perform many source control operations without having to run Visual Studio or a Team Foundation command-line tool.

Work Item Templates

A plug-in to Visual Studio, this tool provides an add-in to the Team menu and a new section on the Work Items page in Team Explorer. With this tool, you can create, apply, capture, set, and organize default work item templates.

Download here.

TFS Team Project Manager

TFS Team Project Manager can help you...

  • Manage build definitions
    • View and delete build definitions
    • Update common properties within build definitions
  • Manage build process templates
    • Understand which build templates are used by which build definitions
    • Unregister existing build process templates
    • Register new or update existing build process templates
  • Manage security
    • Understand which security groups have which members
    • Delete security groups
    • Add security groups
  • Manage source control
    • Understand which projects have which source control settings (multiple check-out, get latest on check-out, check-in notes)
    • Update source control settings
    • Retrieve the latest changesets (e.g. to see which projects are still active)
  • Manage work item configuration
    • Compare work item configurations (i.e. work item type definitions, categories, process configuration) with various sources, e.g. to determine which Process Template was likely used to create which project
    • Understand which projects use which work item types and how many work items there are of each
    • Import new or update existing work item types
    • Manage work item categories
    • Manage process configuration (i.e. common and agile configuration)

 

Download here.

Wednesday, September 26, 2012

Gartner report: Microsoft takes the lead in the Application Lifecycle Management(ALM) space

According to a recent Garner report Microsoft takes the lead in the ALM space.

By virtue of its position in the market as a provider of key platforms and development tools, Microsoft acts as an overall thought leader in the ALM market. However, this breadth and a late start in the ALM market have caused its tools often to lag other products, although it is now introducing innovations. At this point, other than IBM, Microsoft offers the broadest set of ALM functionality in the market. The company tends to deliver new releases every 18 months, but generally needs to coordinate with key platform updates and initiatives. To make up for long development cycles, the product team uses the Microsoft Developer Network (MSDN) to deliver "Power Tools" and other early access software bits.

Microsoft has a broad customer base going from small or midsize businesses (SMBs) up to extremely large enterprises, and its largest sites have more than 10,000 users. Unlike all of the other tools in this Magic Quadrant, Microsoft's is the only one that tightly binds its versioning system to the rest of the ALM planning tool. The single product platform delivery may create functional overlaps with other tools already in your portfolio. Microsoft supports the Visual Studio product line in 13 languages (the second highest of the tools in this Magic Quadrant) and is pushing into cloud deployment for its Team Foundation Server (TFS).

Although Microsoft is one of the only vendors to cover all aspects of the SDLC, its greatest challenge has been support for non-Microsoft development. However, the company has made good strides with support for Eclipse and the ability to extend TFS with Java code. The greatest challenge comes in how to stitch together a mixed environment with developers on non-Microsoft platforms that may have a stack that includes other SCCMs and the steps required to weave this together. TFS is a strong system; however, if your organization doesn't use .NET or other Microsoft technologies, then this will not be your ALM product of choice. As deployment platforms shift to the cloud, this isn't just a Java and .NET issue, and Microsoft will need to continue to demonstrating a long-term commitment to support diverse platform user needs.

Microsoft's products support:

  • Requirements management
  • Project management
  • Quality management
  • Defect management
  • Build management
  • Release management
  • Lab management
  • Change management
  • Task management
  • Modeling

Figure 1.Magic Quadrant for Application Life Cycle Management

Source: Gartner (June 2012)

Tuesday, September 25, 2012

TFS 2012 Web Access: Export Work Item query results to Excel

After upgrading to Team Foundation Server 2012, I got the following question from one of our PM’s:

“In TFS 2010 Web Access I could export my work items to excel. How could I do the same thing in TFS 2012 Web Access?”

Unfortunately there is no direct way of doing this. I know only two possible alternatives/workarounds:

  1. Install Team Explorer 2012. This will give use an extra Team tab in Excel and makes it possible to import the work items directly.
  2. Use the good old copy/paste trick:
    1. Select the work items you want to export from a query result
    2. Press Ctrl+C or open up the popup menu by clicking the down arrow icon on the left of one of the selected work items and click copy (at the bottom)
    3. Press Ctrl+C
    4. Paste to Excel

Anyone with a better alternative?

Monday, September 24, 2012

Windows 8 Camp in a box

For the last months, Microsoft organized Windows 8 camps around the world. The Windows 8 camps are free training events for developers ramping up on Windows Store app development. If you couldn’t make it to any of these camps, I have the following tip for you: Windows 8 Camp in a box.

This download includes the hands-on-labs, presentations, samples and resources from the Windows 8 camps.

image

Friday, September 21, 2012

WinRT: A method was called at an unexpected time. WinRT Information: An eventhandler has already been registered.

For a WinRT application I’m building I decided to support the Share charm. This is done through the use of the DataTransferManager class.
So in the constructor of my page, I added the following code to listen for Share requests:
_manager = DataTransferManager.GetForCurrentView();
_manager.DataRequested += manager_DataRequested;
This seems to work fine but when I moved to another page and navigated back afterwards, I always got the following error message:

“An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was handled in user code. A method was called at an unexpected time.WinRT information: An event handler has already been registered”

clip_image002

I first tried to solve it by unregistering the event handler in the constructor before registering it but this didn’t help:

_manager = DataTransferManager.GetForCurrentView();
_manager.DataRequested -= manager_DataRequested;
_manager.DataRequested += manager_DataRequested;
Instead you have to unregister the event when you navigate away from the page:
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{ 
 var manager = DataTransferManager.GetForCurrentView();
  manager.DataRequested -= manager_DataRequested;
 
 base.OnNavigatingFrom(e);
}
I don’t know if it’s a bug in the WinRT framework but it’s certainly unexpected behavior.

Thursday, September 20, 2012

Team Foundation Server 2012 and Visual Studio Compatibility

After upgrading our internal Team Foundation Server environment to the 2012 version, I got a lot of questions from our development teams about compatibility with different Visual Studio versions.

To help them(and you) here is the compatibility matrix(the full matrix for all TFS versions is available here):

Clients and tools Team Foundation Server 2012
Visual Studio 2012 or Team Explorer 2012 Yes
Visual Studio 2010 or Team Explorer 2010 Yes (1)
Visual Studio 2008 or Team Explorer for Visual Studio Team System 2008 Yes (2)
Team Explorer for Visual Studio 2005 Team System No (3)
Team Web Access for Team Foundation Server 2010 Not applicable
Team Web Access for Visual Studio Team Foundation Server 2012 Yes
MSSCCI 2008 No
MSSCCI 2010 No
MSSCCI 2012 Yes (4)

Important notes about Compatibility:

  1. Visual Studio Team Explorer 2010 needs this patch to connect TFS 2012
  2. Visual Studio Team Explorer 2008 needs this patch to connect to TFS 2010
  3. Visual Studio Team Explorer 2005 cannot connect TFS 2012. Visual Studio 2005 can be connected to TFS 2012 using MSSCCI Provider.
  4. The Microsoft Source Code Control Interface (MSSCCI) Provider 2012 power tool supports Visual Studio Team Foundation Server 2012. For more information, see Microsoft Source Code Control Interface (MSSCCI) Provider 2012 Power Tool.

Wednesday, September 19, 2012

Microsoft Web Essentials: a must have Visual Studio Extension for every web developer

With the release of Visual Studio 2012, Microsoft also updated some of their Visual Studio extensions. One of the extensions I like a lot are the Web Essentials tools and although the live of a web developer becomes a lot easier in Visual Studio 2012, there are still some missing features. Web Essentials 2012 tries to fill this gap.

So what’s new in this version?

  • Option dialog: Now it becomes possible to set the most important options through this dialog.
  • JSHint for JavaScript: JSHint is a really good way of making sure your JavaScript follows certain coding guidelines and best practices.
  • Better LESS and CoffeeScript: The LESS editor has been updated to truly take advantage of LESS. This includes:
    • Support for @import directives
    • Intellisense across imported .less files for Mixins and variables
    • All the validation from the CSS editor now shows up in LESS
    • Both CoffeeScript and LESS now uses the official compilers
    • Compiles and creates a .css/.js file when a LESS/CoffeeScript file is saved in VS
  • JavaScript regions: I’m not big fan of regions, but if you are a believer; Javascript regions is now also a part of the 2012 version
  • Re-embed base64 dataURIs:  allows you to keep your base64 dataURI’s up-to-date with the original image file as it changes.
  • Vendor help for @-directives: Vendor specific validation and Smart Tags are now also available for @-directives.
  • New performance validation: Three new validators have been added that analyses the CSS for general performance issues. They validation the following:
    • Small images should be inlined (base64 embedded)
    • Don’t use the universal selector (the star)
    • Don’t over qualify ID selectors

Of course the list of new features, bug fixes,… is a lot longer, have a look at Mads Kristensen blog for all the info.

Tuesday, September 18, 2012

Error when trying to publish Azure application: Server failed to authenticate the request.

Last week I wanted to deploy an Azure application. So I used the publish options inside Visual Studio to start the deployment process. But after a few seconds it failed with the following error message:

“Server failed to authenticate the request.”

I double checked my credentials, downloaded a new publish contract, I even created another account to test it with other credentials. Nothing helped…

Until I saw in the authentication header that the provided time was not correct. I noticed that the clock on my development machine was 20 minutes behind the real time. Because the UTC time on my local machine was too far out from what the Azure servers say, they revoked my request.

I updated my local machine time and publishing succeeded without any issues.

Monday, September 17, 2012

Storyboarding in Visual Studio 2012: now also for iOS, iPhone & iPad

One of the great new tools in the Visual Studio ALM ecosystem is the Powerpoint Storyboarding. It allows you to create great screen mockups in a familiar user interface(Powerpoint).

Figure 3

Last week Microsoft released three new sets of storyboarding shapes on the Visual Studio Gallery.

Common iOS Icons

iPhone controls

iPad controls

Friday, September 14, 2012

The Transient Fault Handling Application Block

While looking for some good error handling strategies for cloud solutions, I found the following Microsoft Patterns & Practices Application Block: The Transient Fault Handling Application Block.

From the site:

The Microsoft Enterprise Library Transient Fault Handling Application Block lets developers make their applications more resilient by adding robust transient fault handling logic. Transient faults are errors that occur because of some temporary condition such as network connectivity issues or service unavailability. Typically, if you retry the operation that resulted in a transient error a short time later, you find that the error has disappeared.

Different services can have different transient faults, and different applications require different fault handling strategies. The Transient Fault Handling Application Block encapsulates information about the transient faults that can occur when you use the following Windows Azure services in your application:

  • SQL Azure
  • Windows Azure Service Bus
  • Windows Azure Storage
  • Windows Azure Caching Service

The Transient Fault Handling Application Block enables the developer to select from the following retry strategies:

  • Incremental
  • Fixed interval
  • Exponential back-off

The Enterprise Library Transient Fault Handling Application Block includes the following features:

  • You can select from an extensible collection of error detection strategies for cloud-based services, and an extensible collection of retry strategies.
  • You can use the graphical Enterprise Library configuration tool to manage configuration settings.
  • You can extend the block by adding error detection strategies for other services or by adding custom retry strategies.

The Transient Fault Handling Application Block uses detection strategies to identify all known transient error conditions. You can use one of the built-in detection strategies for SQL Azure, Windows Azure Storage, Windows Azure Caching, or the Windows Azure Service Bus. You can also define detection strategies for any other services that your application uses.

Some possible retry strategies:

  • Fixed interval: Retry four times at one-second intervals
  • Incremental interval: Retry four times, waiting one second before the first retry, then two seconds before the second retry, then three seconds before the third retry, and four seconds before the fourth retry.
  • Exponential back off: Retry four times, waiting two seconds before the first retry, then four seconds before the second retry, then eight seconds before the third retry, and sixteen seconds before the fourth retry.

And here is a sample:

using Microsoft.Practices.TransientFaultHandling;
using Microsoft.Practices.TransientFaultHandling.RetryStrategies;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling.AzureStorage;

// Define your retry strategy: retry 3 times, 1 second apart.
var retryStrategy = new FixedInterval(3, TimeSpan.FromSeconds(1));

// Define your retry policy using the retry strategy and the Windows Azure storage
// transient fault detection strategy.
var retryPolicy =
new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

// Do some work that may result in a transient fault.
try
{
// Call a method that uses Windows Azure storage and which may
// throw a transient exception.
retryPolicy.ExecuteAction(
() =>
{
this.queue.CreateIfNotExist();
});
}
catch (Exception)
{
// All of the retries failed.
}

Thursday, September 13, 2012

TFS 2012: Some features of Team Web Access are not visible to you.

After upgrading our TFS environment to Team Foundation Server 2012, the first time we logged on  in to TFS Web Access, we got the following message “Some features of Team Web Access are not visible to you”.

This is caused by the licensing model used for Team Web Access. You have 3 possible license levels:

  • Limited:
    • This level of access restricts the user so that they can only view work items that they create in Team Web Access (also known as Work Item Only View). No other features, such as team pages, are available to users in this group.
    • No client access license (CAL) is required for this level of Team Web Access.
  • Standard:
    • This is the default level of access in Team Web Access for your users. Members of this group can view all Team Web Access features except for:
      • sprint planning and backlog views
      • any of the features for requesting feedback from users and managing that feedback
    • A Team Foundation Server (TFS) CAL is required for all users with this level.
  • Full:
    • This level is reserved for users who are licensed to use all features available in Team Web Access, including the sprint planning and backlog management tools and the Request and Manage Feedback tools.
    • To use these features, your user must be licensed for one of the following MSDN subscriptions: Visual Studio Test Professional with MSDN, Visual Studio Premium with MSDN, or Visual Studio Ultimate with MSDN. These MSDN subscriptions each include a TFS CAL for the subscriber.

To add users to the correct group first click “Administer Server”. Then click “Control Panel”, “Web Access” and “Limited”, “Full” or “Standard” depending on the group you want to add your users/AD-groups to.

You can also change the default licensing mode used if you want to.

image

Wednesday, September 12, 2012

Custom web.config transforms

One of the nice features of Visual Studio 2012(and also Visual Studio 2010) is the ability to use Web.config transformations.
However the list of supported transforms is  somewhat limited. I was looking for a way to execute a transformation only if a specific element doesn’t exist yet in your root web.config file. I discovered that Web.config transform engine can be extended to support additional transformations.
On the AppHarbor blog, I found a sample transformation that exactly did what I needed: 
using System.Linq;
using System.Xml;
using Microsoft.Web.Publishing.Tasks;

namespace AppHarbor.TransformTester.Transforms
{
    public class Merge : Transform
    {
        public Merge() : base(TransformFlags.UseParentAsTargetNode)
        {}

        protected override void Apply()
        {
            Apply((XmlElement)TargetNode, (XmlElement)TransformNode);
        }

        public void Apply(XmlElement targetElement, XmlElement transformElement)
        {
            var targetChildElement = targetElement.ChildNodes.OfType<XmlElement>()
                .FirstOrDefault(x => x.LocalName == transformElement.LocalName);
            if (targetChildElement == null)
            {
                targetElement.AppendChild(transformElement);
                return;
            }

            foreach (var transformChildElement in transformElement.ChildNodes
                .OfType<XmlElement>())
            {
                Apply(targetChildElement, transformChildElement);
            }
        }
    }
}
If you want to use this transform you need to add it using the xdt:Import element. You can place that element inside the xml document anywhere immediately under the root element. This element will allow us to utilize our own transform class. It only has 3 possible attributes.

  • namespace – This is the namespace which the transform is contained in  
  • path – This is the full path to the assembly  
  • assembly – This is the assembly name which contains the transform
You can only use one of the two; path and assembly.

So the import will look like this  in your transformation XML:

   

<xdt:Import assembly="AppHarbor.TransformTester" namespace="AppHarbor.TransformTester.Transforms"/>

From that moment one you can start applying it:


<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">    
<connectionStrings xdt:Transform="Merge" />    
 <connectionStrings>        
  <add name="bar" connectionString="value" xdt:Transform="Insert"/>    
 </connectionStrings>
</configuration>


The only disadvantage I think is that you have to install this transform assembly on all developer pc’s if they want to execute these transformations locally.

Tuesday, September 11, 2012

TF30172: You do not have permission to create a new team project.

Last week a colleague tried to create a new team project on our freshly installed Team Foundation Server 2012 environment.

But when he choose the Add new Team Project option from Visual Studio 2010, he got the following error back:

TF30172: You do not have permission to create a new team project.

Don’t be fooled, this error has nothing to do with security. So don’t go check all your permissions, it will not help. Instead open up Team Explorer 2012(or Visual Studio 2012) and create the new project from there.

That’s it!

Monday, September 10, 2012

Windows 8: Setting the application theme

In Windows Phone you had a global Theme setting on your mobile phone which allows you to switch between the dark and light theme. One thing I didn’t like is that you had to use some tricks to detect the currently active Theme setting.

In Windows 8 Microsoft is taking a different approach: there’s no global theme setting, instead it’s up to the developer to decide if her application uses the dark or the light theme.

You can set the current theme by changing the RequestedTheme-attribute on the Application class. This can be done either through code or through XAML.

<Application x:Class="ThemeSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
RequestedTheme="Light">

Friday, September 7, 2012

Windows 8: Use custom fonts

For a Windows 8 app I’m building, I wanted to use a custom font. It took me some time to figure out how to get this working.

So here are the steps:

  1. Add the font file to your project.
  2. Change the Build Action to Content.
  3. Specify the FontFamily using the format: /<path to font file>/<font file>#<font name>

If you don’t know the font name, double click on the font file:

image

A sample:

<TextBlock FontFamily="/Assets/Fonts/Bauhaus93.TTF#Bauhaus 93"/>


 

Thursday, September 6, 2012

TFS: Work Item Field Reference

Are you customizing the Team Foundation Server Work Items? But you don’t have a clue about all the possible fields? Last week I found this blog post by KathrynE.

Here are two new resources you can use to look up a definition and quickly see which fields are written to the relational database and which are stored in the Analysis Services cube. These cover all the fields defined in the process templates that Team Foundation Server 2012 provides.

  • Work Item Field Reference for Visual Studio ALM: Provides an index to all fields used in the default process templates that TFS 2012 provides. Each field links to a topic that describes the field and its default attribute assignments.

For an overview of the attributes that are defined for each field, see Work Item Field Attributes - What You Can and Can't Change.

Wednesday, September 5, 2012

Windows 8: Uniquely identifying a device

For a Windows 8 application I’m building, I needed a way to uniquely identify a user’s device. The best option I found was using the HardwareIdentification value. The only problem it has is that it can change if your system hardware changes(but that’s good enough for me Glimlach)

O yes, here is the code I used:

private string GetHardwareId()
{
var token = HardwareIdentification.GetPackageSpecificToken(null);
var hardwareId = token.Id;
var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

byte[] bytes = new byte[hardwareId.Length];
dataReader.ReadBytes(bytes);

return BitConverter.ToString(bytes);
}

Tuesday, September 4, 2012

Windows 8: Could not initialize secondary tile with provided arguments.

In a Windows 8 application I tried to add a secondary tile when I got the following exception:

“Could not initialize secondary tile with provided arguments.”

I discovered that the issue was cause by the image I specified. I was using a URI pointing to a resource on a website. According to the documentation this is not supported.

The only valid options are:

  • ms-appx:/// : A path within the deployed app package. This path is resolved for languages and DPI plateau supported by the app.
  • ms-appdata:///local/ : A file found in the per-user app storage.

So if you want to use a resource from the web, you have to download it first and add it to the users local storage folder.

Remark: Note that images are supported for secondary tile notification updates.

Monday, September 3, 2012

Windows 8: Cannot await in the body of a catch clause

While I was writing some async code in .NET 4.5, I decided to add some exception handling. So I created a try/catch block and wanted to show a message dialog when an exception occurs.

However when I added an await to wait for the message dialog result, the compiler started throwing exceptions:

Cannotawait

The error message stated: “Cannot await in the body of a catch clause.”

I solved it by introducing a flag bool exceptionOccurred=false; and setting it to true in the catch block. After the catch clause I added some code to check if the flag is true.

catch(FileNotFoundException ex)
{
exceptionOccured=true;
}

if(exceptionOccured)
{
await new MessageDialog().ShowAsync();
}


Anyone with a cleaner solution?