Export (0) Print
Expand All

Manage Users in C#

The following example shows how to add, get, update, and delete a customer’s user with 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.ServiceModel;
using ManageUser.BingAds.CustomerManagement;

namespace ManageUser
{
    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>";

        // Specify the identifier of the customer for managing users

        private static long m_customerId = <CustomerIdGoesHere>; 

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

                User user;

                // Create a new User data object and add it to specified customer
                Console.WriteLine("Adding new User within CustomerId {0}.", m_customerId);
                user = CreateUserData();
                long userId = AddUser(user, m_customerId);

                // Get and print all users managed by the specified customer
                Console.WriteLine("Printing all Users within CustomerId {0}.", m_customerId);
                ICollection<UserInfo> infos = GetUsers(m_customerId);
                foreach (UserInfo info in infos)
                {
                    user = GetUserData((long)info.Id);

                    if (null == user)
                    {
                        Console.WriteLine("Unable to access data for user {0} ({1})\n", info.UserName, info.Id);
                    }
                    else
                    {
                        // Filter out the users
                        // who have been deleted or are inactive.

                        if (user.UserLifeCycleStatus != UserLifeCycleStatus.Deleted &&
                            user.UserLifeCycleStatus != UserLifeCycleStatus.Inactive)
                            PrintUserData(user);
                    }
                }

                // Ensure AddUser succeeded before updating and deleting the same user
                if (userId > 0)
                {
                    // Update the user and print updated details
                    UpdateUser(userId, m_customerId);
                    user = GetUserData(userId);
                    PrintUserData(user);

                    // Delete the recently added and updated user
                    DeleteUser(userId);
                }
                
                _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();
                }
            }
        }


        // Get the information of the user to add.

        static private User CreateUserData()
        {
            User user = new User();
            ContactInfo contact = new ContactInfo();
            Address address = new Address();
            PersonName name = new PersonName();

            address.Line1 = "1234 Washington Place";
            address.Line2 = "Suite 1210";
            address.City = "Woodinville";
            address.StateOrProvince = "WA";
            address.PostalCode = "98068";
            address.CountryCode = "US";
            contact.Address = address;

            contact.ContactByPhone = true;
            contact.Phone1 = "(206) 555-0100 ext. 1234";
            contact.Email = "kim@alpineskihouse.com";
            contact.EmailFormat = EmailFormat.Text;

            user.ContactInfo = contact;

            user.CustomerAppScope = ApplicationType.Advertiser;

            name.FirstName = "Kim";
            name.LastName = "Abercrombie";
            user.Name = name;

            user.Password = "<NewPasswordGoesHere>";
            user.SecretQuestion = SecretQuestion.FatherMiddleName;
            user.SecretAnswer = "Michael";
            user.UserName = "kaberc";

            return user;
        }

        // Add a user to the specified customer.

        static private long AddUser(User user, long customerId)
        {
            AddUserRequest request = new AddUserRequest();
            AddUserResponse response = null;
          
            long[] accountIds = null;

            try
            {
                // If you do not specify Role, the default is the
                // AdvertiserCampaignManager account role. If you do
                // not specify a list of account identifiers, the user
                // will have AdvertiserCampaignManager permission to
                // all accounts that the customer manages.

                // You can set Role to the SuperAdmin customer role;
                // however, to limit the user to a subset of the
                // customers that the reseller manages,
                // you must call the UpdateUserRoles operation.

                request.UserName = m_username;
                request.Password = m_password;
                request.DeveloperToken = m_token;
                request.User = user;
                request.AccountIds = accountIds;
                request.Role = UserRole.AdvertiserCampaignManager;
                request.User.CustomerId = customerId;

                response = _service.AddUser(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                Console.WriteLine("AddUser failed with the following errors:");

                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("AddUser failed with the following errors:");

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    if (1339 == error.Code)
                    {
                        Console.WriteLine("A user with username {0} already exists.", request.User.UserName);
                    }
                    else
                    {
                        Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                    }
                }
            }

            return (null != response) ? response.Id : -1;
        }

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

        static void UpdateUser(long userId, long customerId)
        {
            UpdateUserRequest request = new UpdateUserRequest();
            UpdateUserResponse response = null;
            User user = null;

            user = GetUserData(userId);

            if (null != user)
            {
                // You can update all elements that are not marked as
                // read-only on MSDN. Update the fields as appropriate.
                // This example updates
                // the user's secret question and answer.

                user.SecretQuestion = SecretQuestion.HighSchoolName;
                user.SecretAnswer = "Bainbridge HS";

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

                    response = _service.UpdateUser(request);
                    Console.WriteLine("User {0} ({1}) was successfully updated.", user.UserName, userId);
                }
                catch (FaultException<AdApiFaultDetail> fault)
                {
                    Console.WriteLine("The following errors occurred while updating user, {0} ({1}).", user.UserName, userId);

                    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 update user {0}.\n", userId);

                    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 user
                            // 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 update,
                            // update the elements as appropriate,
                            // and then call the UpdateUser operation.

                            Console.WriteLine("Another user updated the user.\n");
                        }
                        else
                        {
                            Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                        }
                    }
                }
                catch (Exception)
                {
                    // Catching the generic exception that the UpdateRoles
                    // operation threw, so the code can close cleanly
                    // without calling Abort on the service.
                }
            }
        }

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

        static void DeleteUser(long userId)
        {
            DeleteUserRequest request = new DeleteUserRequest();
            DeleteUserResponse response = null;
            User user = null;

            user = GetUserData(userId);

            if (null != user)
            {
                try
                {
                    request.UserName = m_username;
                    request.Password = m_password;
                    request.DeveloperToken = m_token;
                    request.UserId = userId;
                    request.TimeStamp = user.TimeStamp;

                    response = _service.DeleteUser(request);
                    Console.WriteLine("User {0} ({1}) was successfully deleted.", user.UserName, userId);
                }
                catch (FaultException<AdApiFaultDetail> fault)
                {
                    Console.WriteLine("The following errors occurred while deleting user, {0} ({1}).", user.UserName, userId);

                    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 user {0} ({1}).", user.UserName, userId);

                    foreach (OperationError error in fault.Detail.OperationErrors)
                    {
                        if (1001 == error.Code)
                        {
                            Console.WriteLine("You do not have permissions to delete user {0} ({1}).", user.UserName, userId);
                        }
                        else if (510 == error.Code)
                        {
                            // You should consider retrieving the
                            // user 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 DeleteUser with the new time stamp.

                            Console.WriteLine("Another user updated the user before you could delete them.\n");
                        }
                        else if (1341 == error.Code)
                        {
                            // You cannot delete a user who is the
                            // primary user of an account.
                            // Before you can delete users, you must
                            // remove them as the primary user of the
                            // accounts. See the PrimaryUserId element
                            // of the Account object.

                            Console.WriteLine("You cannot delete the user because it is the primary user of one or more accounts.\n");
                        }
                        else
                        {
                            Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                        }
                    }
                }
            }
        }

        // Get a list of the users
        // who belong to the specified customer.

        static ICollection<UserInfo> GetUsers(long customerId)
        {
            GetUsersInfoRequest request = new GetUsersInfoRequest();
            GetUsersInfoResponse response = null;
            ICollection<UserInfo> infos = null;

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

                response = _service.GetUsersInfo(request);

                infos = response.UsersInfo;
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                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)
                {
                    Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code, error.Details);
                }
            }
            return infos;
        }


        // Gets the user data object

        static User GetUserData(long userId)
        {
            GetUserRequest request = new GetUserRequest();
            GetUserResponse response = null;

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

                response = _service.GetUser(request);
            }
            catch (FaultException<AdApiFaultDetail> fault)
            {
                Console.WriteLine("The following error occurred trying to access user {0}.\n", userId);

                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)
                {
                    Console.WriteLine("The following error occurred trying to access user {0}.\n", userId);

                    if (1001 == error.Code)
                    {
                        Console.WriteLine("You do not have permissions to access user {0}.", userId);
                    }
                    else
                    {
                        Console.WriteLine("Error code: {1}\nMessage: {0}\nDetails: {2}\n", error.Message, error.Code,
                                          error.Details);
                    }
                }
            }

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

        // Print some of the user data.

        private static void PrintUserData(User user)
        {
            Console.WriteLine("Name: " + GetUserName(user.Name));
            Console.WriteLine("ID: " + user.Id);
            Console.WriteLine("Address: {0}\n{1,9}{2}, {3} {4}", user.ContactInfo.Address.Line1,
                "", // padding
                user.ContactInfo.Address.City,
                user.ContactInfo.Address.StateOrProvince,
                user.ContactInfo.Address.PostalCode);

            Console.WriteLine("Contact by:");
            Console.WriteLine("\tEmail at " + user.ContactInfo.Email);

            if ((bool)user.ContactInfo.ContactByPhone)
            {
                Console.WriteLine("\tPhone at " + user.ContactInfo.Phone1);
            }
            if ((bool)user.ContactInfo.ContactByPostalMail)
            {
                Console.WriteLine("\tPostal mail sent to the above address ");
            }

            Console.WriteLine("Logon user name: " + user.UserName);
            Console.WriteLine("Status: " + user.UserLifeCycleStatus);
        }

        // Get the user's full name and return it as a string.

        private static string GetUserName(PersonName person)
        {
            string name = person.FirstName;

            if (person.MiddleInitial != null && person.MiddleInitial != string.Empty)
            {
                name += " " + person.MiddleInitial + ".";
            }

            name += " " + person.LastName;

            return name;
        }
    }
}





Community Additions

Show:
© 2014 Microsoft