### ApplyProductPartitionActions Java Example Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/applyproductpartitionactions This Java example shows how to call the applyProductPartitionActions method. It requires the correct SDK setup and configuration. ```java static ApplyProductPartitionActionsResponse applyProductPartitionActions( ArrayOfAdGroupCriterionAction criterionActions) throws RemoteException, Exception { ApplyProductPartitionActionsRequest request = new ApplyProductPartitionActionsRequest(); request.setCriterionActions(criterionActions); return CampaignManagementService.getService().applyProductPartitionActions(request); } ``` -------------------------------- ### Add Product to Catalog Example Source: https://learn.microsoft.com/en-us/advertising/shopping-content/code-example-manage-products This Java example demonstrates how to add a product to a specified catalog using the Microsoft Content API. It includes setup for authentication and API endpoints. ```java package com.microsoft.contentapi.examples; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; import com.microsoft.contentapi.examples.datatransferobjects.*; public class ManageProductsExample { private static String BaseUri = "https://content.api.bingads.microsoft.com/shopping/v9.1"; private static String BmcUri = BaseUri + "/bmc/%s"; private static String ClientState = "ClientStateGoesHere"; private static String ClientId = ""; private static String DeveloperToken = ""; private static String MerchantId = ""; private static String authenticationToken = ""; public static void main(String args[]) throws Exception { try{ // Get the default catalog Catalog defaultCatalog = retrieveDefaultCatalog(); // Add a product to catalog Product testProduct = createTestProduct("My Test Product %s"); // if catalog id is not specified the product will be added to the default catalog, here we are specifying the default explicitly Product addedProduct = AddProduct(defaultCatalog.getId(), testProduct); System.out.println("*** Added product to catalog (catalog.Id=" + defaultCatalog.getId() + ", product.Id=" + addedProduct.getId() + ")***"); Print(addedProduct); ``` -------------------------------- ### Signup Customer and Account (Java) Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-customer-signup This Java snippet shows how to set up a new customer and advertiser account. It includes configuring the customer's market details, business address, currency, and time zone before calling the signup service. Use this when creating new entities for a reseller. ```Java customer.setIndustry(Industry.OTHER); // The primary country where the customer operates. customer.setMarketCountry("US"); // The primary language that the customer uses. customer.setMarketLanguage(LanguageType.ENGLISH); // The name of the customer. customer.setName("Child Customer " + System.currentTimeMillis()); AdvertiserAccount account = new AdvertiserAccount(); // The location where your business is legally registered. // The business address is used to determine your tax requirements. Address businessAddress = new Address(); businessAddress.setBusinessName("Contoso"); businessAddress.setCity("Redmond"); businessAddress.setLine1("One Microsoft Way"); businessAddress.setPostalCode("98052"); businessAddress.setStateOrProvince("WA"); account.setBusinessAddress(businessAddress); // The type of currency that is used to settle the account. // The service uses the currency information for billing purposes. account.setCurrencyCode(CurrencyCode.USD); // The name of the account. account.setName("Child Account " + System.currentTimeMillis()); // The identifier of the customer that owns the account. account.setParentCustomerId((long)user.getCustomerId()); // The TaxInformation (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. account.setTaxInformation(null); // The default time-zone for campaigns in this account. account.setTimeZone(TimeZoneType.PACIFIC_TIME_US_CANADA_TIJUANA); // Signup a new customer and account for the reseller. outputStatusMessage("-----\nSignupCustomer:"); SignupCustomerResponse signupCustomerResponse = CustomerManagementExampleHelper.signupCustomer( customer, account, user.getCustomerId(), null, null); 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: %s", signupCustomerResponse.getCustomerId())); // 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: %s", signupCustomerResponse.getCustomerNumber())); // 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: %s", signupCustomerResponse.getAccountId())); // 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: %s\n", signupCustomerResponse.getAccountNumber())); } catch (Exception ex) { String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out); outputStatusMessage(faultXml); String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out); outputStatusMessage(message); } } } ``` -------------------------------- ### Get Ad Group Criterion By IDs in Java Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/getadgroupcriterionsbyids This Java example shows how to get ad group criterion by IDs. It requires proper setup of SDKs and system parameters. ```java static GetAdGroupCriterionsByIdsResponse getAdGroupCriterionsByIds( ArrayOflong adGroupCriterionIds, java.lang.Long adGroupId, ArrayList criterionType, ArrayList returnAdditionalFields) throws RemoteException, Exception { GetAdGroupCriterionsByIdsRequest request = new GetAdGroupCridterionsByIdsRequest(); request.setAdGroupCriterionIds(adGroupCriterionIds); request.setAdGroupId(adGroupId); request.setCriterionType(criterionType); request.setReturnAdditionalFields(returnAdditionalFields); return CampaignManagementService.getService().getAdGroupCriterionsByIds(request); } ``` -------------------------------- ### SignupCustomer Java Example Source: https://learn.microsoft.com/en-us/advertising/customer-management-service/signupcustomer This Java code demonstrates how to sign up a customer using the CustomerManagementService. Ensure the CustomerManagementService and related objects are properly initialized. ```java static SignupCustomerResponse signupCustomer( Customer customer, AdvertiserAccount account, java.lang.Long parentCustomerId, UserInvitation userInvitation, java.lang.Long userId, User user) throws RemoteException, Exception { SignupCustomerRequest request = new SignupCustomerRequest(); request.setCustomer(customer); request.setAccount(account); request.setParentCustomerId(parentCustomerId); request.setUserInvitation(userInvitation); request.setUserId(userId); request.setUser(user); return CustomerManagementService.getService().signupCustomer(request); } ``` -------------------------------- ### Keyword Planner API Example Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-keyword-planner This Python script demonstrates how to use the Keyword Planner API to get keyword and ad group estimates. It requires authentication setup and initializes the AdInsightService client. ```python print(f" ... and {len(ad_group_estimate.KeywordEstimates) - 5} more keyword estimates") if len(campaign_estimate.AdGroupEstimates) > 3: print(f"\n ... and {len(campaign_estimate.AdGroupEstimates) - 3} more ad group estimates") print("\n" + "=" * 60) print("Keyword planner test completed successfully!") print("=" * 60) except Exception as ex: print(f"Error occurred: {str(ex)}") import traceback traceback.print_exc() if __name__ == '__main__': print("Loading the web service client...") authorization_data = AuthorizationData( account_id=None, customer_id=None, developer_token=DEVELOPER_TOKEN, authentication=None, ) authenticate(authorization_data) ad_insight_service = ServiceClient( service='AdInsightService', version=13, authorization_data=authorization_data, environment=ENVIRONMENT, ) main() ``` -------------------------------- ### Run SearchUserAccounts Example Source: https://learn.microsoft.com/en-us/advertising/guides/walkthrough-desktop-application-java Right-click on SearchUserAccounts.java and select 'Run' to execute the example. This will initiate the authorization process. ```java SearchUserAccounts.java ``` -------------------------------- ### Get Negative Keywords by Entity IDs (PHP) Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/getnegativekeywordsbyentityids This PHP example demonstrates how to call the GetNegativeKeywordsByEntityIds operation. It requires the Bing Ads API PHP client library and proper proxy setup. ```php static function GetNegativeKeywordsByEntityIds( $entityIds, $entityType, $parentEntityId) { $GLOBALS['Proxy'] = $GLOBALS['CampaignManagementProxy']; $request = new GetNegativeKeywordsByEntityIdsRequest(); $request->EntityIds = $entityIds; $request->EntityType = $entityType; $request->ParentEntityId = $parentEntityId; return $GLOBALS['CampaignManagementProxy']->GetService()->GetNegativeKeywordsByEntityIds($request); } ``` -------------------------------- ### C# Batch Request Example Source: https://learn.microsoft.com/en-us/advertising/shopping-content/code-example-create-batch-request This C# example shows how to create and send a batch request to the Content API. It includes setup for authentication, URL construction, and separate calls for batch insert, get, and delete operations. It also includes error handling for common HTTP status codes. ```C# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.IO.Compression; using System.Threading.Tasks; using System.Net; using Content.OAuth; using Newtonsoft.Json; // NuGet Json.NET namespace Batch { class Program { // The client ID and secret that you were given when you // registered your application. private static string clientId = ""; private static string clientSecret = ""; private static string storedRefreshToken = "; public static long catalogId = ; // Used in example to store operation ids. public static List ProductList = new List(); public static int batchOperationId = 0; // The maximum number of objects that you can specify depends upon // the number of product attributes that you specify and whether you // compress the data. If you do not compress the data, // you can specify about 2,000 objects; otherwise, you can specify // about 12,000 objects. // For this example, limit the list to 5 products. public const int MAX_ENTRIES = 5; static void Main(string[] args) { try { var headers = GetCredentialHeaders(); // Build URL with query string and store id. var url = string.Format(BatchUri + queryString, merchantId, catalogId); // A batch operation may include any operation (insert, get, delete); // however, because the operations may not act on the same product, // this example performs the batch operations separately. BatchInsert(url, headers); BatchGet(url, headers); BatchDelete(url, headers); } catch (WebException e) { Console.WriteLine("\n" + e.Message); HttpWebResponse response = (HttpWebResponse)e.Response; // If the request is bad, the API returns the errors in the // body of the request. For cases where the path may be valid, but // the resource does not belong to the user, the API returns not found. if (response != null && (HttpStatusCode.BadRequest == response.StatusCode || HttpStatusCode.NotFound == response.StatusCode || HttpStatusCode.InternalServerError == response.StatusCode)) { using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); reader.Close(); try { var errors = JsonConvert.DeserializeObject(json); PrintErrors(errors.Error.Errors); } catch (Exception deserializeError) { // This case occurs when the path is not valid. if (HttpStatusCode.NotFound == response.StatusCode) { Console.WriteLine("Path not found: " + response.ResponseUri); } else { Console.WriteLine(deserializeError.Message); } } } } } catch (Exception e) { Console.WriteLine("\n" + e.Message); } } ``` -------------------------------- ### SignupCustomer PHP Example Source: https://learn.microsoft.com/en-us/advertising/customer-management-service/signupcustomer This PHP code snippet shows how to initiate the SignupCustomer operation. It requires the CustomerManagementProxy to be set up correctly. ```php static function SignupCustomer( $customer, $account, $parentCustomerId, $userInvitation, $userId, $user) { $GLOBALS['Proxy'] = $GLOBALS['CustomerManagementProxy']; $request = new SignupCustomerRequest(); $request->Customer = $customer; $request->Account = $account; $request->ParentCustomerId = $parentCustomerId; $request->UserInvitation = $userInvitation; $request->UserId = $userId; $request->User = $user; return $GLOBALS['CustomerManagementProxy']->GetService()->SignupCustomer($request); } ``` -------------------------------- ### Web Service Client Setup and Authentication Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-client-links This section demonstrates the setup for the web service client, including authentication using AuthorizationData and initializing the ServiceClient. This is typically run when the script is executed directly. ```python if __name__ == '__main__': print("Loading the web service client...") authorization_data = AuthorizationData( account_id=None, customer_id=None, developer_token=DEVELOPER_TOKEN, authentication=None, ) authenticate(authorization_data) customer_service = ServiceClient( service='CustomerManagementService', version=13, authorization_data=authorization_data, environment=ENVIRONMENT, ) main(authorization_data) ``` -------------------------------- ### Get Ad Groups By IDs in Java Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/getadgroupsbyids This Java code example shows how to fetch ad groups using their IDs. It requires proper setup of campaign ID, ad group IDs, and additional fields. ```java static GetAdGroupsByIdsResponse getAdGroupsByIds( java.lang.Long campaignId, ArrayOflong adGroupIds, ArrayList returnAdditionalFields) { GetAdGroupsByIdsRequest request = new GetAdGroupsByIdsRequest(); request.setCampaignId(campaignId); request.setAdGroupIds(adGroupIds); request.setReturnAdditionalFields(returnAdditionalFields); return CampaignManagementService.getService().getAdGroupsByIds(request); } ``` -------------------------------- ### Create Brand Kit Recommendation in Python Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/createbrandkitrecommendation This Python example demonstrates creating a brand kit recommendation. Ensure the CampaignManagementService and necessary variables are defined. ```python response=campaignmanagement_service.CreateBrandKitRecommendation( AccountId=AccountId, FinalUrl=FinalUrl) ``` -------------------------------- ### Get Customer Information (Java) Source: https://learn.microsoft.com/en-us/advertising/customer-management-service/getcustomersinfo This Java example shows how to fetch customer details using the Bing Ads SDK. It requires proper setup of system parameters and SDK version. The method handles potential remote exceptions. ```java static GetCustomersInfoResponse getCustomersInfo( java.lang.String customerNameFilter, int topN) throws RemoteException, Exception { GetCustomersInfoRequest request = new GetCustomersInfoRequest(); request.setCustomerNameFilter(customerNameFilter); request.setTopN(topN); return CustomerManagementService.getService().getCustomersInfo(request); } ``` -------------------------------- ### SignupCustomer C# Example Source: https://learn.microsoft.com/en-us/advertising/customer-management-service/signupcustomer Use this C# code to asynchronously sign up a new customer. Ensure you have the necessary CustomerManagementService client and request objects. ```csharp public async Task SignupCustomerAsync( Customer customer, AdvertiserAccount account, long? parentCustomerId, UserInvitation userInvitation, long? userId, User user) { var request = new SignupCustomerRequest { Customer = customer, Account = account, ParentCustomerId = parentCustomerId, UserInvitation = userInvitation, UserId = userId, User = user }; return (await CustomerManagementService.CallAsync((s, r) => s.SignupCustomerAsync(r), request)); } ``` -------------------------------- ### Get Operation Example Source: https://learn.microsoft.com/en-us/advertising/shopping-content/manage-products For get operations, set the 'method' to 'get' and specify the 'productId' of the offer you want to retrieve. ```json { "batchId": "456", "merchantId": "98765", "method": "get", "productId": "http://www.contoso.com/womens-tshirt" } ``` -------------------------------- ### CSV Example for App Install Ad Label Source: https://learn.microsoft.com/en-us/advertising/bulk-service/app-install-ad-label This CSV example demonstrates how to apply a label to an app install ad. Ensure valid Id and Parent Id values are provided. ```csv Type,Status,Id,Parent Id,Campaign,Ad Group,Client Id,Modified Time,Name,Description,Label,Color Format Version,,,,,,,,6.0,,, App Install Ad Label,,-22,-11112,,,ClientIdGoesHere,,,,,, ``` -------------------------------- ### C# Example for Managing Products Source: https://learn.microsoft.com/en-us/advertising/shopping-content/code-example-manage-products This comprehensive C# example demonstrates the full lifecycle of product management, including authentication, adding, retrieving, listing, and deleting products. It utilizes the Bing Ads SDK and requires valid client ID, developer token, refresh token, and merchant ID. ```csharp using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Security.Cryptography; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using Microsoft.BingAds; using Newtonsoft.Json; namespace Products { public class ManageProductExample { private const string BaseUri = "https://content.api.bingads.microsoft.com/shopping/v9.1"; private const string BmcUri = BaseUri + "/bmc/{0}"; private const string ClientState = "ClientStateGoesHere"; private static string ClientId = ""; private static string DeveloperToken = ""; private static string RefreshToken = ""; private static string MerchantId = ""; private static OAuthDesktopMobileAuthCodeGrant OAuth; public static void Main() { try { OAuth = AuthenticateWithOAuth(); // Get the default catalog. // Note that getting catalog information is an expensive call and should be limited. The example // includes this call simply to demonstrate using the call. If you don't specify a catalog, the // product is automatically written to the default catalog, so getting the catalog ID is only useful // if you're adding the product to a non-default catalog. Catalog defaultCatalog = ListCatalogs().FirstOrDefault(cat => cat.IsDefault == true); // Add a product to the catalog Product testProduct = GetTestProduct("My Test Product ({0})"); // If catalog id is not specified, the product is added to the default catalog. Product addedProduct = AddProduct(defaultCatalog.Id, testProduct); Console.WriteLine("*** Added product to catalog (catalog.Id=" + defaultCatalog.Id + ", product.Id=" + addedProduct.Id + ")***"); Print(addedProduct); Console.WriteLine("*** / End of added product (catalog.Id=" + defaultCatalog.Id + ", product.Id=" + addedProduct.Id + ")***"); Console.WriteLine(); // Retrieve a product by id Product retrievedProduct = GetProduct(addedProduct.Id); Console.WriteLine("*** Retrieved product (product.Id=" + retrievedProduct.Id + ")***"); Print(retrievedProduct); Console.WriteLine("*** / End retrieved product (product.Id=" + retrievedProduct.Id + ")***"); Console.WriteLine(); // List products Console.WriteLine("*** Listing products ***"); foreach (Product product in ListProducts()) { Print(product); } Console.WriteLine("*** / End of listing products ***"); Console.WriteLine(); // Delete product Console.WriteLine("*** Deleting Product (" + addedProduct.Id + ") ***"); DeleteProduct(addedProduct.Id); Console.WriteLine("*** / Deleting Product Done (" + addedProduct.Id + ") ***"); } // Catch authentication exceptions catch (OAuthTokenRequestException ex) { OutputStatusMessage(string.Format("OAuthTokenRequestException Message:\n{0}", ex.Message)); if (ex.Details != null) { OutputStatusMessage(string.Format("OAuthTokenRequestException Details:\nError: {0}\nDescription: {1}", ex.Details.Error, ex.Details.Description)); } } catch (HttpRequestException ex) { OutputStatusMessage(ex.Message); } Console.Write("Press enter to exit"); Console.ReadLine(); } // List catalogs public static string CatalogsUri = BmcUri + "/catalogs"; public static string CatalogUri = CatalogsUri + "/{1}"; public static IEnumerable ListCatalogs() { string url = string.Format(CatalogsUri, MerchantId); CatalogCollection catalogs = Request("GET", url); return catalogs?.Catalogs ?? new List(); } // List products public static string ListUri = BmcUri + "/products"; ``` -------------------------------- ### SignupCustomer Python Example Source: https://learn.microsoft.com/en-us/advertising/customer-management-service/signupcustomer This Python example demonstrates calling the SignupCustomer operation. It assumes the customermanagement_service object is configured. ```python response=customermanagement_service.SignupCustomer( Customer=Customer, Account=Account, ParentCustomerId=ParentCustomerId, UserInvitation=UserInvitation, UserId=UserId, User=User) ``` -------------------------------- ### Add App Install Goal CSV Example Source: https://learn.microsoft.com/en-us/advertising/bulk-service/app-install-goal This CSV example demonstrates how to add a new app install goal record using the Bulk service. Ensure the 'Format Version' is set to 6.0. ```csv Type,Id,Attribution Model Type,Count Type,Exclude From Bidding,Goal Category,Is Enhanced Conversions Enabled,Name,Conversion Currency Code,Revenue Value,Revenue Type,Scope,UET Tag Id,Status,View Through Conversion Window In Minutes,Conversion Window In Minutes,Category Expression,Category Operator,Action Expression,Action Operator,Label Expression,Label Operator,Event Value,Event Value Operator,URL Expression,URL Operator,Minimum Duration In Second,App Platform,App Id,Minimum Pages Viewed Format Version,,,,,,,6.0,,,,,,,,,,,,,,,,,,,,,, AppInstall Goal,,,,False,Download,False,GoalE,USD,1,FixedValue,Account,,Active,150,367,,,,,,,,,,,,Android,qazwsx, ``` -------------------------------- ### C# Example: Batch Product Update Source: https://learn.microsoft.com/en-us/advertising/shopping-content/code-example-batch-product-update This C# example demonstrates how to update the pricing and availability for multiple products in a batch using the Content API. Ensure you have the necessary OAuth credentials and store information. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading.Tasks; using System.Net; using Content.OAuth; // Reference to CodeGrantFlow DLL simple OAuth example using Newtonsoft.Json; // NuGet Json.NET using System.Globalization; namespace Catalogs { class Program { // The application ID that you were given when you // registered your application. private static string clientId = ""; private static string storedRefreshToken = ""; private static CodeGrantOauth tokens = null; private static DateTime tokenExpiration; private static string devToken = ""; private static string storeCode = "online"; private static string[] productIds = new[] { "", "" }; // URI templates used to update product pricing. public const string BaseUri = "https://content.api.bingads.microsoft.com/shopping/v9.1"; public static string BmcUri = BaseUri + "/bmc/{0}"; public static string InventoryBatchUri = BmcUri + "/inventory/batch"; // Your store ID. public static ulong merchantId = ; // Suppress NULL when serializing objects. public static JsonSerializerSettings jsonSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }; static void Main(string[] args) { try { var headers = GetCredentialHeaders(); // Build the inventory endpoint. var url = string.Format(InventoryBatchUri, merchantId); // Create a list of products to update. This example shows one // product in the batch. // The product must specify both price and availability. // Sale price and effective date are optional. If missing, // sale price and effective data are removed from the product. var batch = new Batch() { Entries = new List() { new Entry() { BatchId = 1, StoreCode = storeCode, ProductId = productIds[0], Inventory = new Product() { Price = new Price() { Value = 4567, Currency = "USD" }, Availability = "in stock" } }, new Entry() { BatchId = 2, StoreCode = storeCode, ProductId = productIds[1], Inventory = new Product() { Price = new Price() { Value = 7654, Currency = "USD" }, Availability = "bad in stock" } } } }; // Update the product's price and availability. The response // body contains the Batch object. If a product in the batch // successfully updated, the entry contains the batch ID. If // the product failed to update, the entry contains the batch // ID and error details. var response = AddResource(url, headers, batch); // Check which updates succeeded and which failed. foreach (var entry in response.Entries) { if (entry.Errors == null) { Console.WriteLine("{0} update succeeded\n", batch.Entries[(int)entry.BatchId - 1].ProductId); } else { foreach (var error in entry.Errors.Errors) { Console.WriteLine("{0} update failed", batch.Entries[(int)entry.BatchId - 1].ProductId); ``` -------------------------------- ### Signup Customer and Account Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-customer-signup This snippet shows how to sign up a new customer and account for a reseller. It includes setting up customer and account details and handling potential API exceptions. ```csharp 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, userInvitation: null, userId: null); 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 ex) { OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (FaultException ex) { OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message)))); } catch (Exception ex) { OutputStatusMessage(ex.Message); } } } } ``` -------------------------------- ### Request JSON Example Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/getofflineconversionreports This is an example of the JSON request body for the GetOfflineConversionReports operation. It specifies the start and end dates for the report. ```json { "StartDateUtc": "ValueHere", "EndDateUtc": "ValueHere" } ``` -------------------------------- ### Get Media Metadata By IDs in Java Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/getmediametadatabyids This Java example demonstrates how to get media metadata by IDs. It requires the CampaignManagementService to be available. ```java static GetMediaMetaDataByIdsResponse getMediaMetaDataByIds( ArrayOflong mediaIds, ArrayList returnAdditionalFields) throws RemoteException, Exception { GetMediaMetaDataByIdsRequest request = new GetMediaMetaDataByIdsRequest(); request.setMediaIds(mediaIds); request.setReturnAdditionalFields(returnAdditionalFields); return CampaignManagementService.getService().getMediaMetaDataByIds(request); } ``` -------------------------------- ### Add Videos using Python SDK Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/addvideos This Python example shows how to call the AddVideos service operation. Ensure the campaignmanagement_service object and Videos variable are properly initialized. ```python response=campaignmanagement_service.AddVideos( Videos=Videos) ``` -------------------------------- ### Invite User Example in Java Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-invite-user This Java snippet shows how to set up the necessary components to invite a user. It defines the recipient's email address and includes a placeholder for the main logic. ```java package com.microsoft.bingads.examples.v13; import com.microsoft.bingads.*; import com.microsoft.bingads.v13.customermanagement.*; public class InviteUser extends ExampleBase { // Specify the email address where the invitation should be sent. // The recipient can accept the invitation and sign up // with credentials that differ from the invitation email address. final static java.lang.String UserInviteRecipientEmail = "UserInviteRecipientEmailGoesHere"; public static void main(java.lang.String[] args) { try { ``` -------------------------------- ### Request JSON Example Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/getadgroupsbyids This is an example of the JSON request body for the Get Ad Groups By IDs operation. It includes CampaignId, AdGroupIds, and ReturnAdditionalFields. ```json { "CampaignId": "LongValueHere", "AdGroupIds": [ "LongValueHere" ], "ReturnAdditionalFields": "ValueHere" } ``` -------------------------------- ### Get Bulk Upload Status Request JSON Example Source: https://learn.microsoft.com/en-us/advertising/bulk-service/getbulkuploadstatus This is an example of the JSON body for a GetBulkUploadStatus request. It includes the RequestId to identify the upload. ```json { "RequestId": "ValueHere" } ``` -------------------------------- ### Create Campaign (Python) Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-target-criteria Demonstrates creating a new campaign using the Python SDK, including setting its name, budget, language, and time zone. ```Python import uuid from auth_helper import * from openapi_client.models.campaign import * def main(authorization_data): try: # Create a campaign print("Creating campaign...") campaign = Campaign( name="Women's Shoes " + str(uuid.uuid4()), budget_type=BudgetLimitType.DAILYBUDGETSTANDARD, daily_budget=50.00, languages=['All'], time_zone='PacificTimeUSCanadaTijuana' ) add_campaigns_request = AddCampaignsRequest( account_id=authorization_data.account_id, campaigns=[campaign] ) add_campaigns_response = campaign_service.add_campaigns( add_campaigns_request=add_campaigns_request ) campaign_ids = add_campaigns_response.CampaignIds print(f"Created Campaign ID: {campaign_ids[0]}") if add_campaigns_response.PartialErrors: ``` -------------------------------- ### Search User Accounts in Java Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-search-user-accounts This Java example demonstrates how to get user details, search for accounts the user can access, and retrieve customer pilot features. It includes setting up the service client, defining search predicates, and handling pagination. ```java package com.microsoft.bingads.examples.v13; import java.util.Arrays; import com.microsoft.bingads.*; import com.microsoft.bingads.v13.customermanagement.*; import java.util.ArrayList; import java.util.HashSet; public class SearchUserAccounts extends ExampleBase { public static void main(java.lang.String[] args) { try { authorizationData = getAuthorizationData(); CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient( authorizationData, API_ENVIRONMENT, ICustomerManagementService.class); outputStatusMessage("-----\nGetUser:"); GetUserResponse getUserResponse = CustomerManagementExampleHelper.getUser( null); User user = getUserResponse.getUser(); outputStatusMessage("User:"); CustomerManagementExampleHelper.outputUser(user); outputStatusMessage("CustomerRoles:"); CustomerManagementExampleHelper.outputArrayOfCustomerRole(getUserResponse.getCustomerRoles()); // 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. ArrayOfPredicate predicates = new ArrayOfPredicate(); Predicate predicate = new Predicate(); predicate.setField("UserId"); predicate.setOperator(PredicateOperator.EQUALS); predicate.setValue("" + user.getId()); predicates.getPredicates().add(predicate); Paging paging = new Paging(); paging.setIndex(0); paging.setSize(100); final SearchAccountsRequest searchAccountsRequest = new SearchAccountsRequest(); searchAccountsRequest.setPredicates(predicates); searchAccountsRequest.setPageInfo(paging); outputStatusMessage("-----\nSearchAccounts:"); ArrayOfAdvertiserAccount accounts = CustomerManagementExampleHelper.searchAccounts( predicates, null, paging, null).getAccounts(); outputStatusMessage("Accounts:"); CustomerManagementExampleHelper.outputArrayOfAdvertiserAccount(accounts); ArrayOflong customerIds = new ArrayOflong(); for (AdvertiserAccount account : accounts.getAdvertiserAccounts()) { customerIds.getLongs().add(account.getParentCustomerId()); } ArrayList distinctCustomerIds = new ArrayList(new HashSet(customerIds.getLongs())); for (java.lang.Long customerId : 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("----- GetCustomerPilotFeatures:"); outputStatusMessage(String.format("Requested by CustomerId: %s", customerId)); ArrayOfint featurePilotFlags = CustomerManagementExampleHelper.getCustomerPilotFeatures(customerId).getFeaturePilotFlags(); outputStatusMessage("Customer Pilot flags:"); outputStatusMessage(Arrays.toString(featurePilotFlags.getInts().toArray())); } } catch (Exception ex) { String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out); outputStatusMessage(faultXml); String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out); outputStatusMessage(message); } } } ``` -------------------------------- ### getStartDate Source: https://learn.microsoft.com/en-us/advertising/scripts/reference/adgroup Gets the date when ads in this ad group start serving. ```APIDOC ## getStartDate ### Description Get the date when ads in this ad group start serving. ### Returns #### Success Response - **BingAdsDate** - The date when ads in this ad group start serving. ``` -------------------------------- ### Running the get-started.py Script Source: https://learn.microsoft.com/en-us/advertising/guides/walkthrough-desktop-application-python Execute the Python script from your terminal. You will be prompted for user consent to access your Microsoft Advertising accounts. ```powershell (env) PS C:\dev\python> python.exe .\get-started.py ``` -------------------------------- ### Get Historical Search Count in Java Source: https://learn.microsoft.com/en-us/advertising/ad-insight-service/gethistoricalsearchcount This Java method shows how to get historical search counts. It requires proper setup of the AdInsightService and request object. ```java static GetHistoricalSearchCountResponse getHistoricalSearchCount( ArrayOfstring keywords, java.lang.String language, ArrayOfstring publisherCountries, DayMonthAndYear startDate, DayMonthAndYear endDate, java.lang.String timePeriodRollup, ArrayOfstring devices) throws RemoteException, Exception { GetHistoricalSearchCountRequest request = new GetHistoricalSearchCountRequest(); request.setKeywords(keywords); request.setLanguage(language); request.setPublisherCountries(publisherCountries); request.setStartDate(startDate); request.setEndDate(endDate); request.setTimePeriodRollup(timePeriodRollup); request.setDevices(devices); return AdInsightService.getService().getHistoricalSearchCount(request); } ``` -------------------------------- ### Get Products in a Batch Request Source: https://learn.microsoft.com/en-us/advertising/shopping-content/code-example-create-batch-request This example demonstrates how to retrieve products using a batch GET request. It constructs a `BatchCollection` with 'get' operations for each product ID and processes the response, printing product details or error messages. ```java // Use GET operation on the products inserted by BatchInsert. private static void batchGet(String url, Map headers) throws IOException, CapiException { BatchCollection batchCollection = new BatchCollection(); batchCollection.setEntries(new ArrayList()); batchOperationId = 1; for (String productId : ProductList) { BatchEntry batchEntry = new BatchEntry(batchOperationId++, merchantId, "get", productId, null); batchCollection.getEntries().add(batchEntry); } BatchCollection batchOut = batchRequest(url, headers, batchCollection); for (int i = 0; i < batchOut.getEntries().size(); i++) { if (((BatchEntry) batchOut.getEntries().toArray()[i]).getErrors() != null) { System.out.printf("Failed to get product {0}.\n", ((BatchEntry) batchCollection.getEntries().toArray()[(int)(((BatchEntry) batchOut.getEntries().toArray()[i]).getBatchId())]).getProductId()); printErrors(((BatchEntry) batchOut.getEntries().toArray()[i]).getErrors().getErrors()); } else { if (((BatchEntry) batchOut.getEntries().toArray()[i]).getProduct() == null) { System.out.printf("Product {0} was not found.\n", ((BatchEntry) batchCollection.getEntries().toArray()[(int)(((BatchEntry) batchOut.getEntries().toArray()[i]).getBatchId())]).getProductId()); } else { printProduct(((BatchEntry) batchOut.getEntries().toArray()[i]).getProduct()); System.out.println(); } } } } ``` -------------------------------- ### Python Customer Signup Example Source: https://learn.microsoft.com/en-us/advertising/guides/code-example-customer-signup This snippet shows how to create a new customer account with a business address. It requires the AdvertiserAccount, Address, and SignupCustomerRequest objects, and uses the customer_service.signup_customer method. ```python # Create account with business address business_address = Address( City='Redmond', CountryCode='US', PostalCode='98052', StateOrProvince='WA', Line1='One Microsoft Way' ) account = AdvertiserAccount( BusinessAddress=business_address, CurrencyCode='USDollar', Name=f'Child Account {str(uuid.uuid4())[:8]}', ParentCustomerId=user.CustomerId, TaxInformation=None, TimeZone='PacificTimeUSCanadaTijuana' ) signup_request = SignupCustomerRequest( Customer=customer, Account=account, ParentCustomerId=user.CustomerId ) signup_response = customer_service.signup_customer(signup_request) print("SignupCustomerResponse:") print(f"Customer ID: {signup_response.CustomerId}") print(f"Account ID: {signup_response.AccountId}") print(f"Customer Number: {signup_response.CustomerNumber}") print(f"Account Number: {signup_response.AccountNumber}") assert signup_response.CustomerId is not None assert signup_response.AccountId is not None assert signup_response.AccountNumber is not None assert signup_response.CustomerNumber is not None print(f"\nNew Customer ID: {signup_response.CustomerId}") print(f"New Account ID: {signup_response.AccountId}") print(f"New Customer Number: {signup_response.CustomerNumber}") print(f"New Account Number: {signup_response.AccountNumber}") except Exception as ex: print(f"Error occurred: {str(ex)}") import traceback traceback.print_exc() ``` ```python if __name__ == '__main__': import uuid print("Loading the web service client...") authorization_data = AuthorizationData( account_id=None, customer_id=None, developer_token=DEVELOPER_TOKEN, authentication=None, ) authenticate(authorization_data) customer_service = ServiceClient( service='CustomerManagementService', version=13, authorization_data=authorization_data, environment=ENVIRONMENT, ) main(authorization_data) ``` -------------------------------- ### Response JSON Example Source: https://learn.microsoft.com/en-us/advertising/campaign-management-service/getadgroupsbyids This is an example of a JSON response for the Get Ad Groups By IDs operation. It shows the structure for AdGroups and PartialErrors, applicable when BiddingScheme is CommissionBiddingScheme and Setting is AISearchSetting. ```json { "AdGroups": [ { "AdGroupType": "ValueHere", "AdRotation": { "EndDate": "ValueHere", "StartDate": "ValueHere", "Type": "ValueHere" }, "AdScheduleUseSearcherTimeZone": "ValueHere", "AudienceAdsBidAdjustment": IntValueHere, "BiddingScheme": { "Type": "CommissionBiddingScheme", "CommissionRate": DoubleValueHere }, "CommissionRate": { "RateAmount": { "Amount": DoubleValueHere } }, "CpcBid": { "Amount": DoubleValueHere }, "CpmBid": { "Amount": DoubleValueHere }, "CpvBid": { "Amount": DoubleValueHere }, "EndDate": { "Day": IntValueHere, "Month": IntValueHere, "Year": IntValueHere }, "FinalUrlSuffix": "ValueHere", "ForwardCompatibilityMap": [ { "key": "ValueHere", "value": "ValueHere" } ], "FrequencyCapSettings": [ { "CapValue": IntValueHere, "TimeGranularity": "ValueHere" } ], "Id": "LongValueHere", "Language": "ValueHere", "McpaBid": { "Amount": DoubleValueHere }, "MultimediaAdsBidAdjustment": IntValueHere, "Name": "ValueHere", "Network": "ValueHere", "PercentCpcBid": { "RateAmount": { "Amount": DoubleValueHere } }, "PrivacyStatus": "ValueHere", "Settings": [ { "Type": "AISearchSetting", "AISearchEnabled": "ValueHere", "AutoGeneratedImageOptOut": "ValueHere", "AutoGeneratedTextOptOut": "ValueHere", "FinalUrlExpansionOptOut": "ValueHere", "SearchTermMatchingOptOut": "ValueHere" } ], "StartDate": { "Day": IntValueHere, "Month": IntValueHere, "Year": IntValueHere }, "Status": "ValueHere", "TrackingUrlTemplate": "ValueHere", "UrlCustomParameters": { "Parameters": [ { "Key": "ValueHere", "Value": "ValueHere" } ] }, "UseOptimizedTargeting": "ValueHere", "UsePredictiveTargeting": "ValueHere" } ], "PartialErrors": [ { "Code": IntValueHere, "Details": "ValueHere", "ErrorCode": "ValueHere", "FieldPath": "ValueHere", "ForwardCompatibilityMap": [ { "key": "ValueHere", "value": "ValueHere" } ], "Index": IntValueHere, "Message": "ValueHere", "Type": "EditorialError", "Appealable": "ValueHere", "DisapprovedText": "ValueHere", "Location": "ValueHere", "PublisherCountry": "ValueHere", "ReasonCode": IntValueHere } ] } ```