Export (0) Print
Expand All

Optimize Bids in C#

This example shows how to get the bid opportunities which have not expired for the specified account using the following Optimizer service operations.

This example has been developed and run within the environment described in Getting Started Using C# and Visual Basic with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;

using OptimizeBids.BingAds.Optimizer;

namespace OptimizeBids
{
    class Program
    {
        private static OptimizerServiceClient _service;

        // Specify your credentials.

        private const string UserName = "<UserNameGoesHere>";
        private const string Password = "<PasswordGoesHere>";
        private const string DeveloperToken = "<DeveloperTokenGoesHere>";
        private const long AccountId = <AccountIdGoesHere>;
        private const long AdgroupId = <AdGroupIdGoesHere>;
        private const long CampaignId = <CampaignIdGoesHere>;


        static void Main()
        {
            try
            {
                _service = new OptimizerServiceClient("BasicHttpBinding_IOptimizerService");

                // Get the bid opportunities which have not expired for the specified account.

                IList<BidOpportunity> opportunities = GetBidOpportunities(AccountId, AdgroupId, CampaignId);
                IList<string> opportunityKeys = new List<string>();

                if (opportunities.Count == 0)
                {
                    Console.WriteLine("There are not any bid opportunities for the specified account.");
                }
                else
                {
                    foreach (var opportunity in opportunities)
                    {
                        // Add the first 10,000 opportunity keys to an array

                        if (opportunity != null && opportunityKeys.ToArray().Length < 10000)
                        {
                            Console.WriteLine("OpportunityKey: {0}", opportunity.OpportunityKey);
                            opportunityKeys.Add(opportunity.OpportunityKey);
                        }
                    }

                    // Apply the suggested bid opportunities.

                    ApplyOpportunities(AccountId, opportunityKeys);
                }

                _service.Close();
            }
            catch (CommunicationException e)
            {
                Console.WriteLine(e.Message);

                if (e.InnerException != null)
                {
                    Console.WriteLine("\n" + e.InnerException.Message);
                }

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

                if (_service != null)
                {
                    _service.Abort();
                }
            }
            catch (Exception e)
            {
                // Ignore fault exceptions that we already caught.

                if (!(e.InnerException is FaultException))
                {
                    Console.WriteLine(e.Message);
                }

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

        // Gets the bid opportunities which have not expired for the specified account.

        static IList<BidOpportunity> GetBidOpportunities(long accountId, long adGroupId, long campaignId)
        {
            try
            {
                var request = new GetBidOpportunitiesRequest
                    {
                        UserName = UserName,
                        Password = Password,
                        DeveloperToken = DeveloperToken,
                        AccountId = accountId,
                        AdGroupId = adGroupId,
                        CampaignId = campaignId
                    };

                return _service.GetBidOpportunities(request).Opportunities;
            }
            // Optimizer service operations can throw AdApiFaultDetail.
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("The operation failed with the following faults:\n");

                // If the AdApiError array is not null, the following are examples of error codes that may be found.
                foreach (AdApiError error in fault.Detail.Errors)
                {
                    Console.WriteLine("AdApiError");
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case 0:     // InternalError
                            break;
                        case 105:   // InvalidCredentials
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                throw new Exception("", fault);
            }
            // Optimizer service operations can throw ApiFaultDetail.
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("The operation failed with the following faults:\n");

                // If the BatchError array is not null, the following are examples of error codes that may be found.
                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    Console.WriteLine("BatchError at Index: {0}", error.Index);
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case ErrorCodes.InternalError:
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                // If the OperationError array is not null, the following are examples of error codes that may be found.
                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    Console.WriteLine("OperationError");
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case ErrorCodes.InternalError:
                            break;
                        case ErrorCodes.UserIsNotAuthorized:
                            break;
                        case ErrorCodes.InvalidAccountId:
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                throw new Exception("", fault);
            }
        }

        // Apply opportunties for the specified account.

        static void ApplyOpportunities(long accountId, IEnumerable<string> opportunityKeys)
        {
            try
            {
                var request = new ApplyOpportunitiesRequest
                    {
                        UserName = UserName,
                        Password = Password,
                        DeveloperToken = DeveloperToken,
                        AccountId = accountId,
                        OpportunityKeys = opportunityKeys.ToArray()
                    };

                _service.ApplyOpportunities(request);

            }
            // Optimizer service operations can throw AdApiFaultDetail.
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("The operation failed with the following faults:\n");

                // If the AdApiError array is not null, the following are examples of error codes that may be found.
                foreach (AdApiError error in fault.Detail.Errors)
                {
                    Console.WriteLine("AdApiError");
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case 0:     // InternalError
                            break;
                        case 105:   // InvalidCredentials
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                throw new Exception("", fault);
            }
            // Optimizer service operations can throw ApiFaultDetail.
            catch (FaultException<ApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("The operation failed with the following faults:\n");

                // If the BatchError array is not null, the following are examples of error codes that may be found.
                foreach (BatchError error in fault.Detail.BatchErrors)
                {
                    Console.WriteLine("BatchError at Index: {0}", error.Index);
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case ErrorCodes.InternalError:
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                // If the OperationError array is not null, the following are examples of error codes that may be found.
                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    Console.WriteLine("OperationError");
                    Console.WriteLine("Code: {0}\nError Code: {1}\nMessage: {2}\n", error.Code, error.ErrorCode, error.Message);

                    switch (error.Code)
                    {
                        case ErrorCodes.InternalError:
                            break;
                        case ErrorCodes.UserIsNotAuthorized:
                            break;
                        case ErrorCodes.InvalidAccountId:
                            break;
                        default:
                            Console.WriteLine("Please see MSDN documentation for more details about the error code output above.");
                            break;
                    }
                }

                throw new Exception("", fault);
            }
        }
    }
}

Community Additions

Show:
© 2014 Microsoft