public async override Task RunAsync(AuthorizationData authorizationData) { try { ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment; CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(this.OutputStatusMessage); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>(authorizationData, environment); var getUserResponse = await CustomerManagementExampleHelper.GetUserAsync(null, true); var user = getUserResponse.User; // Only a user with the aggregator role (33) can sign up new customers. // If the user does not have the aggregator role, then do not continue. if (!getUserResponse.CustomerRoles.Select(role => role.RoleId).Contains(33)) { OutputStatusMessage("Only a user with the aggregator role (33) can sign up new customers."); return; } // For Customer.CustomerAddress and Account.BusinessAddress, you can use the same address // as your aggregator user, although you must set Id and TimeStamp to null. var userAddress = user.ContactInfo.Address; userAddress.Id = null; userAddress.TimeStamp = null; var customer = new Customer { // The primary business segment of the customer, for example, automotive, food, or entertainment. Industry = Industry.Other, // The primary country where the customer operates. This country will be the // default country for ad groups in the customer’s campaigns. MarketCountry = "US", // The primary language that the customer uses. This language will be the // default language for ad groups in the customer’s campaigns. MarketLanguage = LanguageType.English, // The name of the customer. This element can contain a maximum of 100 characters. Name = "Child Customer " + DateTime.UtcNow, }; var account = new AdvertiserAccount { // The location where your business is legally registered. // The business address is used to determine your tax requirements. BusinessAddress = new Address { BusinessName = "Contoso", City = "Redmond", Line1 = "One Microsoft Way", CountryCode = "US", PostalCode = "98052", StateOrProvince = "WA", }, // The type of currency that is used to settle the account. The service uses the currency information for billing purposes. CurrencyCode = CurrencyCode.USD, // Optionally you can set up each account with auto tagging. // The AutoTagType is an account level setting that determines whether to append or replace // the supported UTM tracking codes within the final URL of ads delivered. The default value is 'Inactive', and // Bing Ads will not append any UTM tracking codes to your ad or keyword final URL. AutoTagType = AutoTagType.Inactive, // The name of the account. The name can contain a maximum of 100 characters and must be unique within the customer. Name = "Child Account " + DateTime.UtcNow, // The identifier of the customer that owns the account. In the Bing Ads API operations // that require a customer identifier, this is the identifier that you set the CustomerId SOAP header to. ParentCustomerId = (long)user.CustomerId, // The list of key and value strings for tax information. // The TaxId (VAT identifier) is optional. If specified, The VAT identifier must be valid // in the country that you specified in the BusinessAddress element. Without a VAT registration // number or exemption certificate, taxes might apply based on your business location. TaxInformation = null, // The time-zone value to use for campaigns in this account. TimeZone = TimeZoneType.PacificTimeUSCanadaTijuana, }; // Signup a new customer and account for the reseller. var signupCustomerResponse = await CustomerManagementExampleHelper.SignupCustomerAsync( customer, account, user.CustomerId); OutputStatusMessage(string.Format("New Customer and Account:\n")); // This is the identifier that you will use to set the CustomerId // element in most of the Bing Ads API service operations. OutputStatusMessage(string.Format("\tCustomerId: {0}", signupCustomerResponse.CustomerId)); // The read-only system-generated customer number that is used in the Bing Ads web application. // The customer number is of the form, Cnnnnnnn, where nnnnnnn is a series of digits. OutputStatusMessage(string.Format("\tCustomerNumber: {0}", signupCustomerResponse.CustomerNumber)); // This is the identifier that you will use to set the AccountId and CustomerAccountId // elements in most of the Bing Ads API service operations. OutputStatusMessage(string.Format("\tAccountId: {0}", signupCustomerResponse.AccountId)); // The read-only system generated account number that is used to identify the account in the Bing Ads web application. // The account number has the form xxxxxxxx, where xxxxxxxx is a series of any eight alphanumeric characters. OutputStatusMessage(string.Format("\tAccountNumber: {0}", signupCustomerResponse.AccountNumber)); } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description)); } // Catch Customer Management service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (Exception ex) { OutputStatusMessage(ex.Message); } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { OutputStatusMessage("You must edit this example to provide the email address (UserInviteRecipientEmail) for " + "the user invitation."); OutputStatusMessage("You must use Super Admin credentials to send a user invitation."); ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment; CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper( OutputStatusMessageDefault: this.OutputStatusMessage); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>( authorizationData: authorizationData, environment: environment); // Prepare to invite a new user var userInvitation = new UserInvitation { // The identifier of the customer this user is invited to manage. // The AccountIds element determines which customer accounts the user can manage. CustomerId = authorizationData.CustomerId, // Users with account level roles such as Advertiser Campaign Manager can be restricted to specific accounts. // Users with customer level roles such as Super Admin can access all accounts within the user's customer, // and their access cannot be restricted to specific accounts. AccountIds = null, // The user role, which determines the level of access that the user has to the accounts specified in the AccountIds element. // The identifier for an advertiser campaign manager is 16. RoleId = 16, // The email address where the invitation should be sent. Email = UserInviteRecipientEmail, // The first name of the user. FirstName = "FirstNameGoesHere", // The last name of the user. LastName = "LastNameGoesHere", // The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS. Lcid = LCID.EnglishUS, }; // Once you send a user invitation, there is no option to rescind the invitation using the API. // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Microsoft Advertising web application. OutputStatusMessage("-----\nSendUserInvitation:"); var userInvitationId = (await CustomerManagementExampleHelper.SendUserInvitationAsync( userInvitation: userInvitation))?.UserInvitationId; OutputStatusMessage(string.Format("Sent new user invitation to {0}.", UserInviteRecipientEmail)); // It is possible to have multiple pending invitations sent to the same email address, // which have not yet expired. It is also possible for those invitations to have specified // different user roles, for example if you sent an invitation with an incorrect user role // and then sent a second invitation with the correct user role. The recipient can accept // any of the invitations. The Bing Ads API does not support any operations to delete // pending user invitations. After you invite a user, the only way to cancel the invitation // is through the Microsoft Advertising web application. You can find both pending and accepted invitations // in the Users section of Accounts & Billing. // Since a recipient can accept the invitation with credentials that differ from // the invitation email address, you cannot determine with certainty the mapping from UserInvitation // to accepted User. You can only determine whether the invitation has been accepted or has expired. // The SearchUserInvitations operation returns all pending invitations, whether or not they have expired. // Accepted invitations are not included in the SearchUserInvitations response. var predicate = new Predicate { Field = "CustomerId", Operator = PredicateOperator.In, Value = authorizationData.CustomerId.ToString(CultureInfo.InvariantCulture) }; OutputStatusMessage("-----\nSearchUserInvitations:"); var userInvitations = (await CustomerManagementExampleHelper.SearchUserInvitationsAsync( predicates: new[] { predicate }))?.UserInvitations; OutputStatusMessage("UserInvitations:"); CustomerManagementExampleHelper.OutputArrayOfUserInvitation(userInvitations); // After the invitation has been accepted, you can call GetUsersInfo and GetUser to access the Microsoft Advertising user details. // Once again though, since a recipient can accept the invitation with credentials that differ from // the invitation email address, you cannot determine with certainty the mapping from UserInvitation // to accepted User. OutputStatusMessage("-----\nGetUsersInfo:"); var usersInfo = (await CustomerManagementExampleHelper.GetUsersInfoAsync( customerId: authorizationData.CustomerId, statusFilter: null))?.UsersInfo; OutputStatusMessage("UsersInfo:"); CustomerManagementExampleHelper.OutputArrayOfUserInfo(usersInfo); foreach (var info in usersInfo) { OutputStatusMessage("-----\nGetUser:"******"User:"******"CustomerRoles:"); CustomerManagementExampleHelper.OutputArrayOfCustomerRole(getUserResponse.CustomerRoles); } } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description)); } // Catch Customer Management AdApiFaultDetail service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } // Catch Customer Management ApiFault service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } // Catch other .NET framework exceptions catch (Exception ex) { OutputStatusMessage(ex.Message); } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { OutputStatusMessage("You must edit this example to provide the email address (UserInviteRecipientEmail) for " + "the user invitation."); OutputStatusMessage("You must use Super Admin credentials to send a user invitation.\n"); ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment; CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(this.OutputStatusMessage); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>(authorizationData, environment); // Prepare to invite a new user var userInvitation = new UserInvitation { // The identifier of the customer this user is invited to manage. // The AccountIds element determines which customer accounts the user can manage. CustomerId = authorizationData.CustomerId, // Users with account level roles such as Advertiser Campaign Manager can be restricted to specific accounts. // Users with customer level roles such as Super Admin can access all accounts within the user's customer, // and their access cannot be restricted to specific accounts. AccountIds = null, // The user role, which determines the level of access that the user has to the accounts specified in the AccountIds element. // The identifier for an advertiser campaign manager is 16. RoleId = 16, // The email address where the invitation should be sent. This element can contain a maximum of 100 characters. Email = UserInviteRecipientEmail, // The first name of the user. This element can contain a maximum of 40 characters. FirstName = "FirstNameGoesHere", // The last name of the user. This element can contain a maximum of 40 characters. LastName = "LastNameGoesHere", // The locale to use when sending correspondence to the user by email or postal mail. The default is EnglishUS. Lcid = LCID.EnglishUS, }; // Once you send a user invitation, there is no option to rescind the invitation using the API. // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Bing Ads web application. var userInvitationId = (await CustomerManagementExampleHelper.SendUserInvitationAsync(userInvitation))?.UserInvitationId; OutputStatusMessage(string.Format("Sent new user invitation to {0}.\n", UserInviteRecipientEmail)); // It is possible to have multiple pending invitations sent to the same email address, // which have not yet expired. It is also possible for those invitations to have specified // different user roles, for example if you sent an invitation with an incorrect user role // and then sent a second invitation with the correct user role. The recipient can accept // any of the invitations. The Bing Ads API does not support any operations to delete // pending user invitations. After you invite a user, the only way to cancel the invitation // is through the Bing Ads web application. You can find both pending and accepted invitations // in the Users section of Accounts & Billing. // Since a recipient can accept the invitation and sign into Bing Ads with a Microsoft account different // than the invitation email address, you cannot determine with certainty the mapping from UserInvitation // to accepted User. You can search by the invitation ID (returned by SendUserInvitations), // only to the extent of finding out whether or not the invitation has been accepted or has expired. // The SearchUserInvitations operation returns all pending invitations, whether or not they have expired. // Accepted invitations are not included in the SearchUserInvitations response. // This example searches for all user invitations of the customer that you manage, // and then filters the search results to find the invitation sent above. // Note: In this example the invitation (sent above) should be active and not expired. You can set a breakpoint // and then either accept or delete the invitation in the Bing Ads web application to change the invitation status. var predicate = new Predicate { Field = "CustomerId", Operator = PredicateOperator.In, Value = authorizationData.CustomerId.ToString(CultureInfo.InvariantCulture) }; var userInvitations = (await CustomerManagementExampleHelper.SearchUserInvitationsAsync(new[] { predicate }))?.UserInvitations; OutputStatusMessage("Existing UserInvitation(s):\n"); CustomerManagementExampleHelper.OutputArrayOfUserInvitation(userInvitations); // Determine whether the invitation has been accepted or has expired. // If you specified a valid InvitationId, and if the invitation is not found, // then the recipient has accepted the invitation. // If the invitation is found, and if the expiration date is later than the current date and time, // then the invitation is still pending and has not yet expired. var pendingInvitation = userInvitations.SingleOrDefault(invitation => invitation.Id == userInvitationId && DateTime.Compare(invitation.ExpirationDate.ToUniversalTime(), DateTime.UtcNow) > 0); // You can send a new invitation if the invitation was either not found, has expired, // or the user has accepted the invitation. This example does not send a new invitation if the // invitationId was found and has not yet expired, i.e. the invitation is pending. if (pendingInvitation == null) { // Once you send a user invitation, there is no option to rescind the invitation using the API. // You can delete a pending invitation in the Accounts & Billing -> Users tab of the Bing Ads web application. userInvitationId = (await CustomerManagementExampleHelper.SendUserInvitationAsync(userInvitation))?.UserInvitationId; OutputStatusMessage(string.Format("Sent new user invitation to {0}.\n", UserInviteRecipientEmail)); } else { OutputStatusMessage(string.Format("UserInvitationId {0} is pending.\n", userInvitationId)); } // After the invitation has been accepted, you can call GetUsersInfo and GetUser to access the Bing Ads user details. // Once again though, since a recipient can accept the invitation and sign into Bing Ads with a Microsoft account // different than the invitation email address, you cannot determine with certainty the mapping from UserInvitation // to accepted User. With the user ID returned by GetUsersInfo or GetUser, you can call DeleteUser to remove the user. var usersInfo = (await CustomerManagementExampleHelper.GetUsersInfoAsync( authorizationData.CustomerId, null))?.UsersInfo; var confirmedUserInfo = usersInfo.SingleOrDefault(info => info.UserName == UserInviteRecipientEmail); // If a user has already accepted an invitation, you can call GetUser to view all user details. if (confirmedUserInfo != null) { var getUserResponse = (await CustomerManagementExampleHelper.GetUserAsync(confirmedUserInfo.Id, true)); OutputStatusMessage("Found Requested User Details (Not necessarily related to above Invitation ID(s):"); CustomerManagementExampleHelper.OutputUser(getUserResponse.User); OutputStatusMessage("Role Ids:"); OutputStatusMessage(string.Join("; ", getUserResponse.CustomerRoles.Select(role => string.Format("{0}", role.RoleId)))); } } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description)); } // Catch Customer Management AdApiFaultDetail service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } // Catch Customer Management ApiFault service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } // Catch other .NET framework exceptions catch (Exception ex) { OutputStatusMessage(ex.Message); } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment; CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper( OutputStatusMessageDefault: this.OutputStatusMessage); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>( authorizationData: authorizationData, environment: environment); OutputStatusMessage("-----\nGetUser:"******"User:"******"CustomerRoles:"); CustomerManagementExampleHelper.OutputArrayOfCustomerRole(getUserResponse.CustomerRoles); // Search for the accounts that the user can access. // To retrieve more than 100 accounts, increase the page size up to 1,000. // To retrieve more than 1,000 accounts you'll need to add paging. var predicate = new Predicate { Field = "UserId", Operator = PredicateOperator.Equals, Value = user.Id.ToString() }; var paging = new Paging { Index = 0, Size = 100 }; OutputStatusMessage("-----\nSearchAccounts:"); var accounts = (await CustomerManagementExampleHelper.SearchAccountsAsync( predicates: new[] { predicate }, ordering: null, pageInfo: paging))?.Accounts.ToArray(); OutputStatusMessage("Accounts:"); CustomerManagementExampleHelper.OutputArrayOfAdvertiserAccount(accounts); HashSet <long> distinctCustomerIds = new HashSet <long>(); foreach (var account in accounts) { distinctCustomerIds.Add(account.ParentCustomerId); } foreach (var customerId in distinctCustomerIds) { // You can find out which pilot features the customer is able to use. // Each account could belong to a different customer, so use the customer ID in each account. OutputStatusMessage("-----\nGetCustomerPilotFeatures:"); OutputStatusMessage(string.Format("Requested by CustomerId: {0}", customerId)); var featurePilotFlags = (await CustomerManagementExampleHelper.GetCustomerPilotFeaturesAsync( customerId: customerId)).FeaturePilotFlags; OutputStatusMessage("Customer Pilot flags:"); OutputStatusMessage(string.Join("; ", featurePilotFlags.Select(flag => string.Format("{0}", flag)))); } } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description)); } // Catch Customer Management service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (Exception ex) { OutputStatusMessage(ex.Message); } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment; CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(this.OutputStatusMessage); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>(authorizationData, environment); var getUserResponse = await CustomerManagementExampleHelper.GetUserAsync(null, true); var user = getUserResponse.User; // Search for the Bing Ads accounts that the user can access. var predicate = new Predicate { Field = "UserId", Operator = PredicateOperator.Equals, Value = user.Id.ToString() }; var paging = new Paging { Index = 0, Size = 10 }; var request = new SearchAccountsRequest { Ordering = null, PageInfo = paging, Predicates = new[] { predicate } }; var accounts = (await CustomerManagementExampleHelper.SearchAccountsAsync( new[] { predicate }, null, paging ))?.Accounts.ToArray(); OutputStatusMessage("The user can access the following Bing Ads accounts: \n"); foreach (var account in accounts) { CustomerManagementExampleHelper.OutputAdvertiserAccount(account); // You can find out which pilot features the customer is able to use. // Each account could belong to a different customer, so use the customer ID in each account. var featurePilotFlags = (await CustomerManagementExampleHelper.GetCustomerPilotFeaturesAsync(account.ParentCustomerId)).FeaturePilotFlags; OutputStatusMessage("Customer Pilot flags:"); OutputStatusMessage(string.Join("; ", featurePilotFlags.Select(flag => string.Format("{0}", flag)))); } } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description)); } // Catch Customer Management service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (Exception ex) { OutputStatusMessage(ex.Message); } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { OutputStatusMessage("You must edit the ManageClient.cs file to provide the ClientAccountId for " + "the client link."); OutputStatusMessage("When adding a client link, the client link's ManagingCustomerId is set to the CustomerId of the current " + "authenticated user, who must be a Super Admin of the agency."); OutputStatusMessage("Login as an agency Super Admin user to send a client link invitation, " + "or unlink an existing client link."); OutputStatusMessage("Login as a client Super Admin user to accept a client link invitation.\n"); CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(this.OutputStatusMessage); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>(authorizationData); UpdateClientLinksResponse updateClientLinksResponse = null; // Specify the client link search criteria var pageInfo = new Paging { Index = 0, // The first page Size = 100 // The first 100 client links for this page of results }; var ordering = new OrderBy { Field = OrderByField.Number, Order = SortOrder.Ascending }; var predicate = new Predicate { Field = "ClientAccountId", Operator = PredicateOperator.In, Value = ClientAccountId.ToString(CultureInfo.InvariantCulture) }; // Search for client links that match the specified criteria. var clientLinks = (await CustomerManagementExampleHelper.SearchClientLinksAsync( new[] { predicate }, new[] { ordering }, pageInfo ))?.ClientLinks; // Determine whether the agency is already managing the specified client account. // If a link exists with status either Active, LinkInProgress, LinkPending, // UnlinkInProgress, or UnlinkPending, the agency may not initiate a duplicate client link. ClientLink clientLink; var newLinkRequired = true; if (clientLinks.Count > 0) { clientLink = clientLinks[0]; OutputStatusMessage(string.Format("Current ClientLink Status: {0}.\n", clientLink.Status)); switch (clientLink.Status) { // The agency may choose to initiate the unlink process, // which would terminate the existing relationship with the client. case ClientLinkStatus.Active: clientLink.Status = ClientLinkStatus.UnlinkRequested; updateClientLinksResponse = await CustomerManagementExampleHelper.UpdateClientLinksAsync(new[] { clientLink }); OutputStatusMessage("UpdateClientLinks : UnlinkRequested.\n"); newLinkRequired = false; break; // Waiting on a system status transition or waiting for the StartDate. case ClientLinkStatus.LinkAccepted: OutputStatusMessage("The status is transitioning towards LinkInProgress.\n"); newLinkRequired = false; break; // Waiting on a system status transition. case ClientLinkStatus.LinkInProgress: OutputStatusMessage("The status is transitioning towards Active.\n"); newLinkRequired = false; break; // When the status is LinkPending, either the agency or client may update the status. // The agency may choose to cancel the client link invitation; however, in this example // the client will accept the invitation. // If the client does not accept or decline the invitation within 30 days, and if the agency // does not update the status to LinkCanceled, the system updates the status to LinkExpired. case ClientLinkStatus.LinkPending: /* * clientLink.Status = ClientLinkStatus.LinkCanceled; * updateClientLinksResponse = UpdateClientLinks(new[] { clientLink }); * WriteMessage(string.Format("The agency updated status: LinkCanceled.\n"); */ clientLink.Status = ClientLinkStatus.LinkAccepted; updateClientLinksResponse = await CustomerManagementExampleHelper.UpdateClientLinksAsync(new[] { clientLink }); OutputStatusMessage("UpdateClientLinks: LinkAccepted.\n"); newLinkRequired = false; break; // Waiting on a system status transition. case ClientLinkStatus.UnlinkInProgress: OutputStatusMessage("The status is transitioning towards Inactive.\n"); newLinkRequired = false; break; // Waiting on a system status transition. case ClientLinkStatus.UnlinkPending: OutputStatusMessage("The status is transitioning towards Inactive.\n"); newLinkRequired = false; break; // The link lifecycle has ended. default: OutputStatusMessage("A new client link invitation is required.\n"); break; } // Print errors if any occurred when updating the client link. if (updateClientLinksResponse != null) { CustomerManagementExampleHelper.OutputArrayOfOperationError(updateClientLinksResponse.OperationErrors); foreach (List <OperationError> operationErrors in updateClientLinksResponse.PartialErrors) { CustomerManagementExampleHelper.OutputArrayOfOperationError(operationErrors); } } } // If no links exist between the agency and specified client account, or a link exists with status // either Inactive, LinkCanceled, LinkDeclined, LinkExpired, or LinkFailed, then the agency must // initiate a new client link. if (newLinkRequired) { clientLink = new ClientLink { ClientAccountId = ClientAccountId, ManagingCustomerId = authorizationData.CustomerId, IsBillToClient = true, Name = "My Client Link", StartDate = null, SuppressNotification = true }; var addClientLinksResponse = await CustomerManagementExampleHelper.AddClientLinksAsync(new[] { clientLink }); // Print errors if any occurred when adding the client link. CustomerManagementExampleHelper.OutputArrayOfOperationError(addClientLinksResponse.OperationErrors); foreach (List <OperationError> operationErrors in addClientLinksResponse.PartialErrors) { CustomerManagementExampleHelper.OutputArrayOfOperationError(operationErrors); } OutputStatusMessage(string.Format("The user attempted to add a new ClientLink.\n")); OutputStatusMessage(string.Format("Login as the client Super Admin to accept the agency's request to manage AccountId {0}.\n", ClientAccountId)); } // Get and print the current client link clientLinks = (await CustomerManagementExampleHelper.SearchClientLinksAsync( new[] { predicate }, new[] { ordering }, pageInfo ))?.ClientLinks; CustomerManagementExampleHelper.OutputArrayOfClientLink(clientLinks); } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description)); } // Catch Customer Management service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (Exception ex) { OutputStatusMessage(ex.Message); } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment; CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper( OutputStatusMessageDefault: this.OutputStatusMessage); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient <ICustomerManagementService>( authorizationData: authorizationData, environment: environment); OutputStatusMessage("-----\nGetUser:"******"User:"******"CustomerRoles:"); CustomerManagementExampleHelper.OutputArrayOfCustomerRole(getUserResponse.CustomerRoles); // Only a user with the aggregator role (33) can sign up new customers. // If the user does not have the aggregator role, then do not continue. if (!getUserResponse.CustomerRoles.Select(role => role.RoleId).Contains(33)) { OutputStatusMessage("Only a user with the aggregator role (33) can sign up new customers."); return; } var customer = new Customer { // The primary business segment of the customer, for example, automotive, food, or entertainment. Industry = Industry.Other, // The primary country where the customer operates. MarketCountry = "US", // The primary language that the customer uses. MarketLanguage = LanguageType.English, // The name of the customer. Name = "Child Customer " + DateTime.UtcNow, }; var account = new AdvertiserAccount { // The location where your business is legally registered. // The business address is used to determine your tax requirements. BusinessAddress = new Address { BusinessName = "Contoso", City = "Redmond", Line1 = "One Microsoft Way", CountryCode = "US", PostalCode = "98052", StateOrProvince = "WA", }, // The type of currency that is used to settle the account. // The service uses the currency information for billing purposes. CurrencyCode = CurrencyCode.USD, // The name of the account. Name = "Child Account " + DateTime.UtcNow, // The identifier of the customer that owns the account. ParentCustomerId = (long)user.CustomerId, // The TaxId (VAT identifier) is optional. If specified, The VAT identifier must be valid // in the country that you specified in the BusinessAddress element. Without a VAT registration // number or exemption certificate, taxes might apply based on your business location. TaxInformation = null, // The default time-zone for campaigns in this account. TimeZone = TimeZoneType.PacificTimeUSCanadaTijuana, }; // Signup a new customer and account for the reseller. OutputStatusMessage("-----\nSignupCustomer:"); var signupCustomerResponse = await CustomerManagementExampleHelper.SignupCustomerAsync( customer : customer, account : account, parentCustomerId : user.CustomerId); OutputStatusMessage("New Customer and Account:"); // This is the identifier that you will use to set the CustomerId // element in most of the Bing Ads API service operations. OutputStatusMessage(string.Format("\tCustomerId: {0}", signupCustomerResponse.CustomerId)); // The read-only system-generated customer number that is used in the Microsoft Advertising web application. // The customer number is of the form, Cnnnnnnn, where nnnnnnn is a series of digits. OutputStatusMessage(string.Format("\tCustomerNumber: {0}", signupCustomerResponse.CustomerNumber)); // This is the identifier that you will use to set the AccountId and CustomerAccountId // elements in most of the Bing Ads API service operations. OutputStatusMessage(string.Format("\tAccountId: {0}", signupCustomerResponse.AccountId)); // The read-only system generated account number that is used to identify the account in the Microsoft Advertising web application. // The account number has the form xxxxxxxx, where xxxxxxxx is a series of any eight alphanumeric characters. OutputStatusMessage(string.Format("\tAccountNumber: {0}", signupCustomerResponse.AccountNumber)); } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description)); } // Catch Customer Management service exceptions catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.AdApiFaultDetail> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (FaultException <Microsoft.BingAds.V12.CustomerManagement.ApiFault> ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (Exception ex) { OutputStatusMessage(ex.Message); } }