Export (0) Print
Expand All

Update User in C#

The following example shows how to get a user and update some elements using the following Customer Management service operations. Additionally this example shows how to update the user role.

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.Text;
using System.ServiceModel;
using UpdateUser.BingAds.CustomerManagement;

namespace UpdateUser
{
    class Program
    {
        private static CustomerManagementServiceClient service = null;

        // Specify your credentials.

        private static string m_password = "<PasswordGoesHere>";
        private static string m_userName = "<UsernameGoesHere>";
        private static string m_token = "<DeveloperTokenGoesHere>";

        // Specify the identifier of the user to update
        // and the customer to which the user belongs.

        private static long m_customerId = <CustomerIdGoesHere>; 
        private static long m_userId = <CustomerIdGoesHere>;

        // Define the integer values for the customer and account roles.
        // UpdateUser uses integer values compared to AddUser,
        // which uses an enumeration to specify the values.

        private const int ADVERTISER_CAMPAIGN_MANAGER_ROLE = 16;
        private const int SUPER_ADMIN_ROLE = 41;


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

                UpdateUser(m_userId, 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();
                }
            }
        }

        // 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;
            GetUserResponse userData = null;

            userData = GetUserData(m_userId);

            if (null != userData)
            {
                user = userData.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, m_userId);

                    ClearAccountRestrictions(m_customerId, m_userId, userData.Accounts);
                    Console.WriteLine("User roles for {0} ({1}) were successfully updated.", user.UserName, m_userId);
                }
                catch (FaultException<AdApiFaultDetail> fault)
                {
                    Console.WriteLine("The following errors occurred while updating user, {0} ({1}).", user.UserName, user.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 update user {0}.\n", user.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 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.
                }
            }
        }


        // Because the update operation is a complete overwrite,
        // you must first get the user's current data, which includes 
        // the time stamp of the previous write operation.

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

                foreach (OperationError error in fault.Detail.OperationErrors)
                {
                    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 response;
        }

        // Removes all access restrictions for a user with an
        // account role or customer role. The user
        // will have access to all accounts or customers
        // that the specified customer owns or manages.

        static void ClearAccountRestrictions(long customerId, long userId, long[] accountIds)
        {
            UpdateUserRolesRequest request = null;
            UpdateUserRolesResponse response = null;

            if (null != accountIds && accountIds.Length > 0)
            {
                request = new UpdateUserRolesRequest();
                request.NewRoleId = ADVERTISER_CAMPAIGN_MANAGER_ROLE;
                request.NewAccountIds = null;

                request.DeleteRoleId = ADVERTISER_CAMPAIGN_MANAGER_ROLE;
                request.DeleteAccountIds = accountIds;

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

                    response = service.UpdateUserRoles(request);
                }
                catch (FaultException<AdApiFaultDetail> fault)
                {
                    Console.WriteLine("The following errors occurred while updating the roles of user {0} ({1}).", userId);

                    foreach (AdApiError error in fault.Detail.Errors)
                    {
                        Console.WriteLine("Error code: {1}\nMessage: {0}\nDetail: {2}\n", error.Message, error.Code, error.Detail);
                    }

                    throw new Exception("The ClearRestrictions method of the UpdateUser example failed.");
                }
                catch (FaultException<ApiFault> fault)
                {
                    Console.WriteLine("The following error occurred while updating the roles of user {0}.\n", userId);

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

                    throw new Exception("The ClearRestrictions method of the UpdateUser example failed.");
                }
            }
        }
    }
}


Community Additions

Show:
© 2015 Microsoft