Changing the Exception Handling for .NET adCenter API Examples

Just letting you know that we'll be changing the exception handling in our adCenter examples for C# and Visual Basic to reflect the WCF recommended approach for exception handling. Please consider doing the same with your implementations if you are not already doing so.

Currently our examples use try/catch/finally and release the client (call the Close() method) in the finally block. The problem is that Close() can throw exceptions. If Close() throws an exception, you must call the Abort() method to ensure that all resources are released; otherwise, you could be leaking resources on the server. The recommended practice is to call Close() within the try block, and call Abort() from the caught exceptions.

For example,

        static void Main(...)
        {
            try
            { 
                service = new CampaignManagementServiceClient("BasicHttpBinding_ICampaignManagementService");
                AddAdGroupsToCampaign(service, ...); 
                service.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);

                if (service != null)
                { 
                    service.Abort();
                } 
            }
            catch (TimeoutException e)
            {
                Console.WriteLine(e.Message);

                if (service != null)
                { 
                    service.Abort();
                } 
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                if (service != null)
                { 
                    service.Abort();
                }
            }
        }

        static void AddAdGroupsToCampaign(service, ...)
        {
            try
            {
                ...

                AddAdGroupsResponse response = service.AddAdGroups(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            { 
                ...  
            }
            catch (FaultException<ApiFaultDetail> fault)
            {
                ... 
            }
        }

 

The following links provide the details from the WCF docs:

Accessing Services Using a WCF Client

Handling Exceptions

Handling exceptions in client applications is straightforward. If a channel is opened, used, and closed inside a try block, then the conversation has succeeded, unless an exception is thrown. Typically, if an exception is thrown the conversation is aborted.

Expected Exceptions

Avoiding Problems with the Using Statement

Thanks and enjoy!