Wednesday, May 14, 2008

Calling a WCF Service

Based on WCF best practices, calling a WCF service should not be wrapped in a using statement as exceptions can be raised (http://msdn2.microsoft.com/en-us/library/aa355056.aspx). Below is a code snippet highlighting the best practice:

ServiceClient client = new ServiceClient();

try
{
client.MyOperation
();
client.Close
();
}
catch (CommunicationException e
)
{
//Handle exception if necessary
client.Abort
();
}
catch (TimeoutException e
)
{
//Handle exception if necessary
client.Abort
();
}
catch (Exception e
)
{
//Handle exception if necessary
client.Abort
();
throw
;
}

However the code to write to do so is quite painful, hence I have written a VS code snippet (wcfproxycall.snippet) to minimize the pain.

To install the code snippet, simply copy the attached snippet to "My Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets"

When you need to call a proxy, type wcfproxycall in your code and hit the Tab key to expand the code snippet.

  • Fill the highlighted fields
  • Use the tab key to navigate to the next field
  • Hit Enter to complete when all fields are filled

No comments: