Export (0) Print
Expand All

Manage Accounts in C#

The following example shows how to get, update, and delete a customer’s account 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 ManageAccount.BingAds.CustomerManagement;

namespace ManageAccount
{
    class Program
    {
        private static CustomerManagementServiceClient _service;

        // Specify your credentials.

        private static string m_username = "<UserNameGoesHere>";
        private static string m_password = "<PasswordGoesHere>";
        private static string m_token = "<DeveloperTokenGoesHere>";

        // Specify the identifier of the customer
        // whose accounts you want to get.

        private static long m_customerId = <CustomerIdGoesHere>; 

        static void Main(string[] args)
        {
            try
            {
                _service = new CustomerManagementServiceClient("BasicHttpBinding_ICustomerManagementService");

                ICollection<AccountInfo> infos = GetAccounts(m_customerId);
                Account account;

                // Print a list of all accounts managed by the customer
                foreach (AccountInfo info in infos)
                {
                    account = GetAccountData((long)info.Id);

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

                // Select one account identifier to demonstrate account update and delete
                long m_accountid = (long)(infos.ToArray()[0].Id);

                Console.WriteLine("Printing Account with identifier {0}.", m_accountid);
                PrintAccountData(GetAccountData(m_accountid));
                
                UpdateAccount(m_accountid);

                Console.WriteLine("Printing Account with identifier {0} after update try.", m_accountid);
                PrintAccountData(GetAccountData(m_accountid));

                DeleteAccount(m_accountid);

                Console.WriteLine("Printing Account with identifier {0} after delete try.", m_accountid);
                PrintAccountData(GetAccountData(m_accountid));

                _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 accounts info that the customer owns and manages

        static ICollection<AccountInfo> GetAccounts(long customerId)
        {
            GetAccountsInfoRequest request = new GetAccountsInfoRequest();
            GetAccountsInfoResponse response = null;
            ICollection<AccountInfo> infos = null;

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

                response = _service.GetAccountsInfo(request);

                if (null == response.AccountsInfo)
                {
                    Console.WriteLine("The customer does not have any accounts.");
                }
                else
                {
                    infos = response.AccountsInfo.ToArray();
                }
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                // Log this fault.

                Console.WriteLine("GetAccountsInfo 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("GetAccountsInfo 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 account data that is associated with
        // the specified account identifier.

        static Account GetAccountData(long accountId)
        {
            GetAccountRequest request = new GetAccountRequest();
            GetAccountResponse response = null;

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

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

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

                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("GetAccount({0}) failed with the following faults:\n", accountId);

                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.Account;
        }

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

        static void UpdateAccount(long accountId)
        {
            UpdateAccountRequest request = new UpdateAccountRequest();
            UpdateAccountResponse response = null;
            Account account = null;

            account = GetAccountData(accountId);

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

                account.Name = account.Name + "_UPDATED";

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

                    // You cannot update or delete an account
                    // that has been deleted.

                    if (AccountLifeCycleStatus.Inactive != account.AccountLifeCycleStatus)
                    {
                        response = _service.UpdateAccount(request);

                        Console.WriteLine("Account with identifier {0} was successfully updated.", accountId);
                    }
                    else
                    {
                        Console.WriteLine("Account with identifier {0} is Inactive and may not be updated.", accountId);
                    }
                }
                catch (FaultException<AdApiFaultDetail> fault)
                {
                    Console.WriteLine("The following errors occurred while updating account {0} ({1}).", account.Name, account.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)
                {
                    Console.WriteLine("The following errors occurred trying to update account {0}.\n", account.Id);

                    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
                            // account object again to get the new
                            // time stamp and data. You can then show
                            // the latest updates to the user to
                            // confirm that they want to continue with
                            // their update.
                            // If so, update the elements as appropriate
                            // and call the UpdateAccount operation.

                            Console.WriteLine("Another user updated the account.\n");
                        }
                        else
                        {
                            Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                        }
                    }
                }
            }
        }

        // Delete the specified account.
        // The delete will fail if another user updates the account
        // between the time that you retrieved the account object and
        // the time that you called the DeleteAccount operation.

        static void DeleteAccount(long accountId)
        {
            DeleteAccountRequest request = new DeleteAccountRequest();
            DeleteAccountResponse response = null;
            Account account = null;

            account = GetAccountData(accountId);

            if (null != account)
            {
                try
                {
                    request.UserName = m_username;
                    request.Password = m_password;
                    request.DeveloperToken = m_token;
                    request.AccountId = accountId;
                    request.TimeStamp = account.TimeStamp;

                    response = _service.DeleteAccount(request);

                    Console.WriteLine("Account {0} ({1}) was successfully deleted.", account.Name, accountId);
                }
                catch (FaultException<AdApiFaultDetail> fault)
                {
                    Console.WriteLine("The following errors occurred while deleting account, {0} ({1}).", account.Name, account.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)
                {
                    Console.WriteLine("The following error occurred trying to delete account {0} ({1}).", account.Name, account.Id);

                    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 delete account, {0} ({1}).", account.Name, account.Id);
                        }
                        else if (112 == error.Code)
                        {
                            // Because the get operations will return
                            // accounts that have been deleted,
                            // you may want to confirm the account's
                            // status before trying to delete
                            // the account to avoid this error.

                            Console.WriteLine("The account has already been deleted.");
                        }
                        else if (510 == error.Code)
                        {
                            // You should consider retrieving the
                            // account object again to get the
                            // new time stamp and data,
                            // show the latest updates to the user,
                            // and confirm that they want to
                            // continue with their delete.
                            // If so, call the DeleteAccount
                            // operation with the new time stamp.

                            Console.WriteLine("Another user updated the account before you could delete it.\n");
                        }
                        else
                        {
                            Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                        }
                    }
                }
            }
        }

        // Print the contents of the account object.

        private static void PrintAccountData(Account account)
        {
            Console.WriteLine("BillToCustomerId: " + account.BillToCustomerId);
            Console.WriteLine("CountryCode: " + account.CountryCode);
            Console.WriteLine("CurrencyType: " + account.CurrencyType);
            Console.WriteLine("FinancialStatus: " + account.AccountFinancialStatus);
            Console.WriteLine("ID: " + account.Id);
            Console.WriteLine("Language: " + account.Language);
            Console.WriteLine("Name: " + account.Name);
            Console.WriteLine("Number: " + account.Number);
            Console.WriteLine("ParentCustomerId: " + account.ParentCustomerId);
            Console.WriteLine("PaymentMethodId: " + account.PaymentMethodId);
            Console.WriteLine("PrimaryUserId: " + account.PrimaryUserId);
            Console.WriteLine("Status: " + account.AccountLifeCycleStatus);
            Console.WriteLine("Last modified: " +
                              TimeZoneInfo.ConvertTime(account.LastModifiedTime.Value, TimeZoneInfo.Local));
            Console.WriteLine("Last modified by: " + account.LastModifiedByUserId);

            if (AccountType.Advertiser == account.AccountType)
            {
                Console.WriteLine("AgencyContactName: " + ((AdvertiserAccount) account).AgencyContactName);
                Console.WriteLine("AgencyCustomerId: " + ((AdvertiserAccount) account).AgencyCustomerId);
                Console.WriteLine("SalesHouseCustomerId: " + ((AdvertiserAccount) account).SalesHouseCustomerId);
            }

            Console.WriteLine("\n"); // \n X 2
        }
    }
}


Community Additions

Show:
© 2014 Microsoft