Export (0) Print
Expand All

Manage Customers in C#

The following example shows how to get and update customers using the following Customer Management 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 ManageCustomer.BingAds.CustomerManagement;

namespace ManageCustomer
{
    class Program
    {
        private static CustomerManagementServiceClient _service = null;

        // Specify your credentials.

        private static string m_username = "<UserNameGoesHere";
        private static string m_password = "<PasswordGoesHere>";
        private static string m_token = "<DeveloperTokenGoesHere>";
        
        static void Main(string[] args)
        {
            try
            {
                _service = new CustomerManagementServiceClient("BasicHttpBinding_ICustomerManagementService");

                // To filter the list of customers for a specific
                // customer or set of customers whose names begin
                // with the same specific sequence of characters,
                // replace string.empty with the customer’s 
                // name or sequence of characters.

                String filter = String.Empty;
                ICollection<CustomerInfo> infos = GetCustomers(filter);
                Customer customer;

                // Print a list of all customers managed and requested by the user
                Console.WriteLine("Printing all Customers with filter: {0}.", filter);
                foreach (CustomerInfo info in infos)
                {
                    customer = GetCustomerData((long)info.Id);

                    if (null == customer)
                    {
                        Console.WriteLine("Unable to access data for customer {0} ({1})\n", info.Name, info.Id);
                    }
                    else
                    {
                        PrintCustomerData(customer);
                    }
                }

                // Select one customer identifier to demonstrate customer update
                long m_customerid = (long)(infos.ToArray()[0].Id);

                Console.WriteLine("Printing Customer with identifier {0}.", m_customerid);
                PrintCustomerData(GetCustomerData(m_customerid));

                UpdateCustomer(m_customerid);

                Console.WriteLine("Printing Customer with identifier {0} after update try.", m_customerid);
                PrintCustomerData(GetCustomerData(m_customerid));

                _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();
                }
            }
        }

        // Gets the advertising customers that the user
        // has access to and that match the filter criteria.

        static ICollection<CustomerInfo> GetCustomers(string nameFilter)
        {
            GetCustomersInfoRequest request = new GetCustomersInfoRequest();
            GetCustomersInfoResponse response = null;
            ICollection<CustomerInfo> infos = null;

            try
            {
                request.UserName = m_username;
                request.Password = m_password;
                request.DeveloperToken = m_token;

                // Specify the filter criteria.
                // If you do not specify the application scope filter,
                // the list will contain both advertising and publishing
                // customers (if you have customers of both types).

                // If the nameFilter parameter is not an empty string,
                // the operation returns customers
                // whose name begins with the specified filter string.

                // You must specify the number of customers that
                // the operation returns. For example, to get the first 
                // 100 customers that match the filter, set TopN to 100.

                // If you are not a reseller, the list will contain
                // at most one customer object that represents you.

                request.ApplicationScope = ApplicationType.Advertiser;
                request.CustomerNameFilter = nameFilter;
                request.TopN = int.MaxValue;

                response = _service.GetCustomersInfo(request);

                if (null == response.CustomersInfo)
                {
                    Console.WriteLine("There are no customers that match the specified filter criteria.");
                }
                else
                {
                    infos = response.CustomersInfo.ToArray();
                }
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

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

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    Console.WriteLine("Error code: {1}\nMessage: {0}\nDetail: {2}\n", error.Message, error.Code, error.Detail);
                }
            }
            catch (FaultException<ApiFault> fault)
            {
                // Log this fault.

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

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                }
            }
            return infos;
        }

        // Get the customer data associated with
        // the specified customer identifier.

        static Customer GetCustomerData(long customerId)
        {
            GetCustomerRequest request = new GetCustomerRequest();
            GetCustomerResponse response = null;

            try
            {
                request.UserName = m_username;
                request.Password = m_password;
                request.DeveloperToken = m_token;
                request.CustomerId = customerId;

                response = _service.GetCustomer(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetCustomer({0}) failed with the following faults:\n", customerId);

                foreach (AdApiError error in fault.Detail.Errors)
                {
                    Console.WriteLine("Error code: {1}\nMessage: {0}\nDetail: {2}\n", error.Message, error.Code, error.Detail);
                }
            }
            catch (FaultException<ApiFault> fault)
            {
                // Log this fault.

                Console.WriteLine("GetCustomer({0}) failed with the following faults:\n", customerId);

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                }
            }

            return (null == response) ? null : response.Customer;
        }

        // Update the customer's data.
        // The update will fail if another user updated the
        // customer data between the time you retrieved the customer
        // object and the time you called the UpdateCustomer operation.

        static void UpdateCustomer(long customerId)
        {
            UpdateCustomerRequest request = new UpdateCustomerRequest();
            UpdateCustomerResponse response = null;
            Customer customer = null;

            customer = GetCustomerData(customerId);

            if (null != customer)
            {
                // You can update all elements
                // that are not marked as read-only on MSDN.
                // Update the fields as appropriate.
                // This example updates the customer’s address.

                customer.CustomerAddress.Line1 = "6789 Rollingstone";
                customer.CustomerAddress.City = "Redmond";
                customer.CustomerAddress.PostalCode = "98444";

                try
                {
                    request.UserName = m_username;
                    request.Password = m_password;
                    request.DeveloperToken = m_token;
                    request.Customer = customer;

                    response = _service.UpdateCustomer(request);

                    Console.WriteLine("Customer {0} ({1}) was successfully updated.", customer.Name, customerId);
                }
                catch (FaultException<AdApiFaultDetail> fault)
                {
                    Console.WriteLine("The following errors occurred while updating customer, {0} ({1}).", customer.Name, customer.Id);

                    foreach (AdApiError error in fault.Detail.Errors)
                    {
                        Console.WriteLine("Error code: {1}\nMessage: {0}\nDetail: {2}\n", error.Message, error.Code, error.Detail);
                    }
                }
                catch (FaultException<ApiFault> fault)
                {
                    foreach (OperationError error in fault.Detail.OperationErrors)
                    {
                        if (1001 == error.Code)
                        {
                            // You cannot update the read-only
                            // fields, such as the status fields.

                            Console.WriteLine("You do not have permissions to update one or more of the fields.\n");
                        }
                        else if (510 == error.Code)
                        {
                            // You should consider retrieving
                            // the customer object again to get 
                            // the new time stamp and data.
                            // You can then show the latest
                            // updates to the user and confirm
                            // that they want to continue with
                            // their update. If so, update the
                            // elements as appropriate, and call
                            // the UpdateCustomer operation.

                            Console.WriteLine("Another user updated the customer.\n");
                        }
                        else
                        {
                            Console.WriteLine("The following error occurred trying to update customer {0}.\n", customerId);
                            Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                        }
                    }
                }
            }
        }

        // Print the contents of the Customer object.

        static void PrintCustomerData(Customer customer)
        {
            Console.WriteLine("Customer: {0} ({1})", customer.Name, customer.Id);
            Console.WriteLine("Address: {0}\n{1,9}{2}, {3} {4}", customer.CustomerAddress.Line1,
                "", // padding
                customer.CustomerAddress.City,
                customer.CustomerAddress.StateOrProvince,
                customer.CustomerAddress.PostalCode);
            Console.WriteLine("Status: " + customer.CustomerLifeCycleStatus);
            Console.WriteLine("Financial status: " + customer.CustomerFinancialStatus);
            Console.WriteLine("Service level: " + customer.ServiceLevel);
            Console.WriteLine("Industry: " + customer.Industry);
            Console.WriteLine("MarketCountry: " + customer.MarketCountry);
            Console.WriteLine("MarketLanguage: " + customer.MarketLanguage);
            Console.WriteLine("Last modified: " + TimeZoneInfo.ConvertTime(customer.LastModifiedTime.Value, TimeZoneInfo.Local));
            Console.WriteLine("Last modified by: " + customer.LastModifiedByUserId);
            Console.WriteLine("\n"); // \n X 2
        }
    }
}




Community Additions

Show:
© 2014 Microsoft