Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
In diesem Beispiel wird veranschaulicht, wie Sie Bezeichnungen hinzufügen und sie Kampagnen und Anzeigengruppen zuordnen.
Tipp
Verwenden Sie die Sprachauswahl im Dokumentationsheader, um C#, Java, Php oder Python auszuwählen.
Informationen zum Abrufen von Zugriffs- und Aktualisierungstoken für Ihren Microsoft Advertising-Benutzer und Zum ersten Dienstaufruf mithilfe der Bing Ads-API finden Sie im Schnellstarthandbuch . Sie sollten den Leitfaden für die ersten Schritte und exemplarische Vorgehensweisen für Ihre bevorzugte Sprache lesen, z. B. C#, Java, Php und Python.
Unterstützende Dateien für C#-, Java-, Php- und Python-Beispiele sind auf GitHub verfügbar. Sie können jedes Repository klonen oder Codeausschnitte nach Bedarf erneut verwenden.
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;
namespace BingAdsExamplesLibrary.V13
{
/// <summary>
/// How to add labels and associate them with
/// campaigns, ad groups, keywords, and ads.
/// </summary>
public class Labels : ExampleBase
{
public override string Description
{
get { return "Labels | Campaign Management V13"; }
}
protected const int MaxGetLabelsByIds = 1000;
protected const int MaxLabelIdsForGetLabelAssociations = 1;
protected const int MaxEntityIdsForGetLabelAssociations = 100;
protected const int MaxPagingSize = 1000;
public async override Task RunAsync(AuthorizationData authorizationData)
{
try
{
ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;
CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
OutputStatusMessageDefault: this.OutputStatusMessage);
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData: authorizationData,
environment: environment);
// Add an ad group in a campaign. Later we will create labels for them.
// Although not included in this example you can also create labels for ads and keywords.
var campaigns = new[]{
new Campaign
{
BudgetType = BudgetLimitType.DailyBudgetStandard,
DailyBudget = 50,
CampaignType = CampaignType.Search,
Languages = new string[] { "All" },
Name = "Everyone's Shoes " + DateTime.UtcNow,
TimeZone = "PacificTimeUSCanadaTijuana",
},
};
OutputStatusMessage("-----\nAddCampaigns:");
AddCampaignsResponse addCampaignsResponse = await CampaignManagementExampleHelper.AddCampaignsAsync(
accountId: authorizationData.AccountId,
campaigns: campaigns);
long?[] campaignIds = addCampaignsResponse.CampaignIds.ToArray();
BatchError[] campaignErrors = addCampaignsResponse.PartialErrors.ToArray();
OutputStatusMessage("CampaignIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(campaignIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(campaignErrors);
var adGroups = new[] {
new AdGroup
{
Name = "Everyone's Red Shoe Sale",
StartDate = null,
EndDate = new Date {
Month = 12,
Day = 31,
Year = DateTime.UtcNow.Year + 1
},
CpcBid = new Bid { Amount = 0.09 },
}
};
OutputStatusMessage("-----\nAddAdGroups:");
AddAdGroupsResponse addAdGroupsResponse = await CampaignManagementExampleHelper.AddAdGroupsAsync(
campaignId: (long)campaignIds[0],
adGroups: adGroups,
returnInheritedBidStrategyTypes: false);
long?[] adGroupIds = addAdGroupsResponse.AdGroupIds.ToArray();
BatchError[] adGroupErrors = addAdGroupsResponse.PartialErrors.ToArray();
OutputStatusMessage("AdGroupIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(adGroupIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(adGroupErrors);
// Add labels and associate them with the campaign and ad group.
var random = new Random();
var labels = new List<Label>();
for (var labelIndex = 0; labelIndex < 5; labelIndex++)
{
var color = string.Format("#{0:X6}", random.Next(0x100000));
labels.Add(new Label
{
ColorCode = color,
Description = "Label Description",
Name = "Label Name " + color + " " + DateTime.UtcNow
});
}
OutputStatusMessage("-----\nAddLabels:");
AddLabelsResponse addLabelsResponse = await CampaignManagementExampleHelper.AddLabelsAsync(labels);
long?[] nullableLabelIds = addLabelsResponse.LabelIds.ToArray();
BatchError[] labelErrors = addLabelsResponse.PartialErrors.ToArray();
OutputStatusMessage("LabelIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(nullableLabelIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(labelErrors);
var labelIds = GetNonNullableIds(nullableLabelIds);
OutputStatusMessage("-----\nGetLabelsByIds:");
var getLabelsByIdsResponse = await CampaignManagementExampleHelper.GetLabelsByIdsAsync(
labelIds: labelIds,
pageInfo: new Paging
{
Index = 0,
Size = MaxGetLabelsByIds
}
);
var getLabels = getLabelsByIdsResponse.Labels;
labelErrors = getLabelsByIdsResponse.PartialErrors.ToArray();
OutputStatusMessage("Labels:");
CampaignManagementExampleHelper.OutputArrayOfLabel(getLabels);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(labelErrors);
var campaignLabelAssociations = CreateExampleLabelAssociationsByEntityId((long)campaignIds[0], labelIds);
OutputStatusMessage("-----\nAssociating all of the labels with a campaign...");
CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(campaignLabelAssociations);
var setLabelAssociationsResponse = await CampaignManagementExampleHelper.SetLabelAssociationsAsync(
entityType: EntityType.Campaign,
labelAssociations: campaignLabelAssociations);
var adGroupLabelAssociations = CreateExampleLabelAssociationsByEntityId((long)adGroupIds[0], labelIds);
OutputStatusMessage("-----\nAssociating all of the labels with an ad group...");
CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(adGroupLabelAssociations);
setLabelAssociationsResponse = await CampaignManagementExampleHelper.SetLabelAssociationsAsync(
entityType: EntityType.AdGroup,
labelAssociations: adGroupLabelAssociations);
OutputStatusMessage("-----\nUse paging to get all campaign label associations...");
var getLabelAssociationsByLabelIds = await GetLabelAssociationsByLabelIdsHelperAsync(
CampaignManagementExampleHelper,
entityType: EntityType.Campaign,
labelIds: labelIds);
CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);
OutputStatusMessage("-----\nUse paging to get all ad group label associations...");
getLabelAssociationsByLabelIds = await GetLabelAssociationsByLabelIdsHelperAsync(
CampaignManagementExampleHelper: CampaignManagementExampleHelper,
entityType: EntityType.AdGroup,
labelIds: labelIds);
CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);
OutputStatusMessage("-----\nGet label associations for the campaigns...");
var getLabelAssociationsByEntityIds = await GetLabelAssociationsByEntityIdsHelperAsync(
CampaignManagementExampleHelper: CampaignManagementExampleHelper,
entityType: EntityType.Campaign,
entityIds: GetNonNullableIds(campaignIds)
);
CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);
OutputStatusMessage("-----\nGet label associations for the ad groups...");
getLabelAssociationsByEntityIds = await GetLabelAssociationsByEntityIdsHelperAsync(
CampaignManagementExampleHelper: CampaignManagementExampleHelper,
entityType: EntityType.AdGroup,
entityIds: GetNonNullableIds(adGroupIds)
);
CampaignManagementExampleHelper.OutputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);
OutputStatusMessage("-----\nDelete all label associations that we set above...");
// Deleting the associations is not necessary if you are deleting the corresponding campaign(s), as the
// contained ad groups, ads, and associations would also be deleted.
var deleteLabelAssociationsResponse = await CampaignManagementExampleHelper.DeleteLabelAssociationsAsync(
entityType: EntityType.Campaign,
labelAssociations: campaignLabelAssociations);
deleteLabelAssociationsResponse = await CampaignManagementExampleHelper.DeleteLabelAssociationsAsync(
entityType: EntityType.AdGroup,
labelAssociations: adGroupLabelAssociations);
// Delete the account's labels.
OutputStatusMessage("-----\nDeleteLabels:");
var deleteLabelsResponse = await CampaignManagementExampleHelper.DeleteLabelsAsync(
labelIds: labelIds);
foreach (var id in labelIds)
{
OutputStatusMessage(string.Format("Deleted Label Id {0}", id));
}
// Delete the campaign and everything it contains e.g., ad groups and ads.
OutputStatusMessage("-----\nDeleteCampaigns:");
await CampaignManagementExampleHelper.DeleteCampaignsAsync(
accountId: authorizationData.AccountId,
campaignIds: new[] { (long)campaignIds[0] });
OutputStatusMessage(string.Format("Deleted Campaign Id {0}", campaignIds[0]));
}
// 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 Campaign Management service exceptions
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.EditorialApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (Exception ex)
{
OutputStatusMessage(ex.Message);
}
}
private static List<LabelAssociation> CreateExampleLabelAssociationsByEntityId(long entityId, List<long> labelIds)
{
var labelAssociations = new List<LabelAssociation>();
foreach (var labelId in labelIds)
{
labelAssociations.Add(
new LabelAssociation
{
EntityId = entityId,
LabelId = labelId
}
);
}
return labelAssociations;
}
private async Task<List<LabelAssociation>> GetLabelAssociationsByLabelIdsHelperAsync(
CampaignManagementExampleHelper CampaignManagementExampleHelper,
EntityType entityType,
IList<long> labelIds
)
{
var labelAssociations = new List<LabelAssociation>();
var labelIdsPageIndex = 0;
while (labelIdsPageIndex * MaxLabelIdsForGetLabelAssociations < labelIds.Count)
{
var getLabelIds =
labelIds.Skip(labelIdsPageIndex++ * MaxLabelIdsForGetLabelAssociations).Take(MaxLabelIdsForGetLabelAssociations).ToList();
var labelAssociationsPageIndex = 0;
var foundLastPage = false;
while (!foundLastPage)
{
var getLabelAssociationsByLabelIds = await CampaignManagementExampleHelper.GetLabelAssociationsByLabelIdsAsync(
entityType: entityType,
labelIds: getLabelIds,
pageInfo: new Paging
{
Index = labelAssociationsPageIndex++,
Size = MaxPagingSize
}
).ConfigureAwait(continueOnCapturedContext: false);
labelAssociations.AddRange(getLabelAssociationsByLabelIds.LabelAssociations);
foundLastPage = MaxPagingSize > getLabelAssociationsByLabelIds.LabelAssociations.Count;
}
}
return labelAssociations;
}
private async Task<List<LabelAssociation>> GetLabelAssociationsByEntityIdsHelperAsync(
CampaignManagementExampleHelper CampaignManagementExampleHelper,
EntityType entityType,
IList<long> entityIds
)
{
var labelAssociations = new List<LabelAssociation>();
var entityIdsPageIndex = 0;
while (entityIdsPageIndex * MaxEntityIdsForGetLabelAssociations < entityIds.Count)
{
var getEntityIds =
entityIds.Skip(entityIdsPageIndex++ * MaxEntityIdsForGetLabelAssociations).Take(MaxEntityIdsForGetLabelAssociations).ToList();
var getLabelAssociationsByEntityIds = await CampaignManagementExampleHelper.GetLabelAssociationsByEntityIdsAsync(
entityIds: getEntityIds,
entityType: entityType
).ConfigureAwait(continueOnCapturedContext: false);
labelAssociations.AddRange(getLabelAssociationsByEntityIds.LabelAssociations);
}
return labelAssociations;
}
}
}
package com.microsoft.bingads.examples.v13;
import java.util.Random;
import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.List;
import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
public class Labels extends ExampleBase {
static java.lang.Integer MAX_GET_LABELS_BY_IDS = 1000;
static java.lang.Integer MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS = 1;
static java.lang.Integer MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS = 100;
static java.lang.Integer MAX_PAGING_SIZE = 1000;
public static void main(java.lang.String[] args) {
try
{
authorizationData = getAuthorizationData();
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData,
API_ENVIRONMENT,
ICampaignManagementService.class);
// Add an ad group in a campaign. Later we will create labels for them.
// Although not included in this example you can also create labels for ads and keywords.
ArrayOfCampaign campaigns = new ArrayOfCampaign();
Campaign campaign = new Campaign();
campaign.setBudgetType(BudgetLimitType.DAILY_BUDGET_STANDARD);
campaign.setDailyBudget(50.00);
ArrayOfstring languages = new ArrayOfstring();
languages.getStrings().add("All");
campaign.setLanguages(languages);
campaign.setName("Everyone's Shoes " + System.currentTimeMillis());
campaign.setTimeZone("PacificTimeUSCanadaTijuana");
campaigns.getCampaigns().add(campaign);
outputStatusMessage("-----\nAddCampaigns:");
AddCampaignsResponse addCampaignsResponse = CampaignManagementExampleHelper.addCampaigns(
authorizationData.getAccountId(),
campaigns);
ArrayOfNullableOflong campaignIds = addCampaignsResponse.getCampaignIds();
ArrayOfBatchError campaignErrors = addCampaignsResponse.getPartialErrors();
outputStatusMessage("CampaignIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(campaignIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(campaignErrors);
// Add an ad group within the campaign.
ArrayOfAdGroup adGroups = new ArrayOfAdGroup();
AdGroup adGroup = new AdGroup();
adGroup.setName("Everyone's Red Shoe Sale");
adGroup.setStartDate(null);
Calendar calendar = Calendar.getInstance();
adGroup.setEndDate(new com.microsoft.bingads.v13.campaignmanagement.Date());
adGroup.getEndDate().setDay(31);
adGroup.getEndDate().setMonth(12);
adGroup.getEndDate().setYear(calendar.get(Calendar.YEAR));
Bid CpcBid = new Bid();
CpcBid.setAmount(0.09);
adGroup.setCpcBid(CpcBid);
adGroups.getAdGroups().add(adGroup);
outputStatusMessage("-----\nAddAdGroups:");
AddAdGroupsResponse addAdGroupsResponse = CampaignManagementExampleHelper.addAdGroups(
campaignIds.getLongs().get(0),
adGroups,
false);
ArrayOfNullableOflong adGroupIds = addAdGroupsResponse.getAdGroupIds();
ArrayOfBatchError adGroupErrors = addAdGroupsResponse.getPartialErrors();
outputStatusMessage("CampaignIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(adGroupIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(adGroupErrors);
// Add labels and associate them with the campaign and ad group.
Random random = new Random();
ArrayOfLabel labels = new ArrayOfLabel();
for (int labelIndex = 0; labelIndex < 5; labelIndex++)
{
java.lang.String color = String.format("#%06x", random.nextInt(0x100000));
Label label = new Label();
label.setColorCode(color);
label.setDescription("Label Description");
label.setName("Label Name " + color + " " + System.currentTimeMillis());
labels.getLabels().add(label);
}
outputStatusMessage("-----\nAddLabels:");
AddLabelsResponse addLabelsResponse = CampaignManagementExampleHelper.addLabels(labels);
ArrayOfNullableOflong labelIds = addLabelsResponse.getLabelIds();
ArrayOfBatchError labelErrors = addLabelsResponse.getPartialErrors();
outputStatusMessage("LabelIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(labelIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(labelErrors);
ArrayOflong getLabelIds = getNonNullableIds(labelIds);
Paging paging = new Paging();
paging.setIndex(0);
paging.setSize(MAX_GET_LABELS_BY_IDS);
outputStatusMessage("-----\nGetLabelsByIds:");
GetLabelsByIdsResponse getLabelsByIdsResponse = CampaignManagementExampleHelper.getLabelsByIds(
getLabelIds,
paging);
outputStatusMessage("Labels:");
CampaignManagementExampleHelper.outputArrayOfLabel(getLabelsByIdsResponse.getLabels());
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(labelErrors);
ArrayOfLabelAssociation campaignLabelAssociations = createExampleLabelAssociationsByEntityId(
campaignIds.getLongs().get(0),
getLabelIds);
outputStatusMessage("-----\nAssociating all of the labels with a campaign...");
CampaignManagementExampleHelper.outputArrayOfLabelAssociation(campaignLabelAssociations);
SetLabelAssociationsResponse setLabelAssociationsResponse = CampaignManagementExampleHelper.setLabelAssociations(
EntityType.CAMPAIGN,
campaignLabelAssociations);
ArrayOfLabelAssociation adGroupLabelAssociations = createExampleLabelAssociationsByEntityId(
adGroupIds.getLongs().get(0),
getLabelIds);
outputStatusMessage("-----\nAssociating all of the labels with an ad group...");
CampaignManagementExampleHelper.outputArrayOfLabelAssociation(adGroupLabelAssociations);
setLabelAssociationsResponse = CampaignManagementExampleHelper.setLabelAssociations(
EntityType.AD_GROUP,
adGroupLabelAssociations);
outputStatusMessage("-----\nUse paging to get all campaign label associations...");
ArrayOfLabelAssociation getLabelAssociationsByLabelIds = getLabelAssociationsByLabelIdsHelper(
EntityType.CAMPAIGN,
getLabelIds);
CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);
outputStatusMessage("-----\nUse paging to get all ad group label associations...");
getLabelAssociationsByLabelIds = getLabelAssociationsByLabelIdsHelper(
EntityType.AD_GROUP,
getLabelIds);
CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByLabelIds);
outputStatusMessage("-----\nGet label associations for the campaigns...");
ArrayOfLabelAssociation getLabelAssociationsByEntityIds = getLabelAssociationsByEntityIdsHelper(
EntityType.CAMPAIGN,
getNonNullableIds(campaignIds));
CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);
outputStatusMessage("-----\nGet label associations for the ad groups...");
getLabelAssociationsByEntityIds = getLabelAssociationsByEntityIdsHelper(
EntityType.AD_GROUP,
getNonNullableIds(adGroupIds));
CampaignManagementExampleHelper.outputArrayOfLabelAssociation(getLabelAssociationsByEntityIds);
outputStatusMessage("-----\nDelete all label associations that we set above...");
// Deleting the associations is not necessary if you are deleting the corresponding campaign(s), as the
// contained ad groups, keywords, ads, and associations would also be deleted.
DeleteLabelAssociationsResponse deleteLabelAssociationsResponse = CampaignManagementExampleHelper.deleteLabelAssociations(
EntityType.CAMPAIGN,
campaignLabelAssociations);
deleteLabelAssociationsResponse = CampaignManagementExampleHelper.deleteLabelAssociations(
EntityType.AD_GROUP,
adGroupLabelAssociations);
// Deleting the campaign(s) removes the corresponding label associations but not remove the labels.
outputStatusMessage("-----\nDeleteLabels:");
DeleteLabelsResponse deleteLabelsResponse = CampaignManagementExampleHelper.deleteLabels(
getLabelIds);
for (java.lang.Long id : getLabelIds.getLongs())
{
outputStatusMessage(String.format("Deleted Label Id %s", id));
}
// Delete the campaign and everything it contains e.g., ad groups and ads.
outputStatusMessage("-----\nDeleteCampaigns:");
ArrayOflong deleteCampaignIds = new ArrayOflong();
deleteCampaignIds.getLongs().add(campaignIds.getLongs().get(0));
CampaignManagementExampleHelper.deleteCampaigns(
authorizationData.getAccountId(),
deleteCampaignIds);
outputStatusMessage(String.format("Deleted CampaignId %d", deleteCampaignIds.getLongs().get(0)));
}
catch (Exception ex) {
String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
outputStatusMessage(faultXml);
String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
outputStatusMessage(message);
}
}
static ArrayOfLabelAssociation createExampleLabelAssociationsByEntityId(java.lang.Long entityId, ArrayOflong labelIds)
{
ArrayOfLabelAssociation labelAssociations = new ArrayOfLabelAssociation();
for (java.lang.Long labelId : labelIds.getLongs())
{
LabelAssociation labelAssociation = new LabelAssociation();
labelAssociation.setEntityId(entityId);
labelAssociation.setLabelId(labelId);
labelAssociations.getLabelAssociations().add(labelAssociation);
}
return labelAssociations;
}
static ArrayOfLabelAssociation getLabelAssociationsByLabelIdsHelper(
EntityType entityType,
ArrayOflong labelIds
) throws Exception, RemoteException
{
ArrayOfLabelAssociation labelAssociations = new ArrayOfLabelAssociation();
int labelIdsPageIndex = 0;
while (labelIdsPageIndex * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < labelIds.getLongs().size())
{
int startIndex = labelIdsPageIndex++ * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS;
int toIndex = labelIds.getLongs().size() - startIndex - MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < 0 ?
labelIds.getLongs().size() :
startIndex + MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS;
List<java.lang.Long> idSubList = labelIds.getLongs().subList(startIndex, toIndex);
ArrayOflong getLabelIds = new ArrayOflong();
for (java.lang.Long id : idSubList){
getLabelIds.getLongs().add(id);
}
int labelAssociationsPageIndex = 0;
boolean foundLastPage = false;
Paging paging = new Paging();
paging.setSize(MAX_PAGING_SIZE);
while (!foundLastPage)
{
paging.setIndex(labelAssociationsPageIndex++);
GetLabelAssociationsByLabelIdsResponse getLabelAssociationsByLabelIds = CampaignManagementExampleHelper.getLabelAssociationsByLabelIds(
entityType,
getLabelIds,
paging
);
labelAssociations.getLabelAssociations().addAll(getLabelAssociationsByLabelIds.getLabelAssociations().getLabelAssociations());
foundLastPage = MAX_PAGING_SIZE > getLabelAssociationsByLabelIds.getLabelAssociations().getLabelAssociations().size();
}
}
return labelAssociations;
}
static ArrayOfLabelAssociation getLabelAssociationsByEntityIdsHelper(
EntityType entityType,
ArrayOflong entityIds
) throws Exception, RemoteException
{
ArrayOfLabelAssociation labelAssociations = new ArrayOfLabelAssociation();
int entityIdsPageIndex = 0;
while (entityIdsPageIndex * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < entityIds.getLongs().size())
{
int startIndex = entityIdsPageIndex++ * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS;
int toIndex = entityIds.getLongs().size() - startIndex - MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < 0 ?
entityIds.getLongs().size() :
startIndex + MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS;
List<java.lang.Long> idSubList = entityIds.getLongs().subList(startIndex, toIndex);
ArrayOflong getEntityIds = new ArrayOflong();
for (java.lang.Long id : idSubList){
getEntityIds.getLongs().add(id);
}
GetLabelAssociationsByEntityIdsResponse getLabelAssociationsByEntityIds = CampaignManagementExampleHelper.getLabelAssociationsByEntityIds(
getEntityIds,
entityType
);
labelAssociations.getLabelAssociations().addAll(getLabelAssociationsByEntityIds.getLabelAssociations().getLabelAssociations());
}
return labelAssociations;
}
static ArrayOflong getNonNullableIds(ArrayOfNullableOflong nullableIds)
{
ArrayOflong ids = new ArrayOflong();
for (java.lang.Long nullableId : nullableIds.getLongs())
{
ids.getLongs().add(nullableId);
}
return ids;
}
}
<?php
namespace Microsoft\MsAds\Rest\Test\Services;
use Microsoft\MsAds\Rest\ApiException;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AddLabelsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AdGroup;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Bid;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\BudgetLimitType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Campaign;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Date;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\DeleteLabelsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\EntityType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\GetLabelsByIdsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Label;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\LabelAssociation;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Paging;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\SetLabelAssociationsRequest;
use Microsoft\MsAds\Rest\Test\RestApiTestBase;
class LabelsTest extends RestApiTestBase
{
private const MAX_GET_LABELS_BY_IDS = 1000;
private const MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS = 1;
private const MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS = 100;
private const MAX_PAGING_SIZE = 1000;
/**
* @throws ApiException
*/
public function testAddCampaigns()
{
$campaign = (new Campaign())
->setName("Women's Shoes ".self::generateRandomAlphaNumeric())
->setBudgetType(BudgetLimitType::DAILY_BUDGET_STANDARD)
->setDailyBudget(50.00)
->setLanguages(['All'])
->setTimeZone('PacificTimeUSCanadaTijuana');
return self::addCampaignsRequest([$campaign]);
}
/**
* @depends testAddCampaigns
* @throws ApiException
*/
public function testAddAdGroups($campaignIds)
{
print("-----\r\nAdding Ad Groups:\r\n");
$adGroup = (new AdGroup())
->setName("Ad Group Women's Red Shoe Sale".self::generateRandomAlphaNumeric())
->setCpcBid((new Bid())->setAmount(0.09))
->setEndDate((new Date())->setDay(31)->setMonth(12)->setYear(date("Y")));
return self::addAdGroupsRequest($campaignIds[0], [$adGroup]);
}
/**
* @depends testAddCampaigns
* @depends testAddAdGroups
* @throws ApiException
*/
public function testAddLabels()
{
print("-----\r\nAdding Labels:\r\n");
$labels = [];
for ($i = 0; $i < 5; $i++) {
$color = "#".substr("000000".dechex(rand()), -6);
$labels[] = (new Label())
->setColorCode($color)
->setDescription('Label Description')
->setName('Label Name '.$color.' '.self::generateRandomAlphaNumeric());
}
$request = (new AddLabelsRequest())
->setLabels($labels);
$response = self::$campaignManagementServiceApi->addLabels($request);
$labelIds = $response->getLabelIds();
print_r($labelIds);
self::assertNotEmpty($labelIds);
self::assertEmpty($response->getPartialErrors());
return $labelIds;
}
/**
* @depends testAddCampaigns
* @depends testAddAdGroups
* @depends testAddLabels
* @throws ApiException
*/
public function testGetLabelsByIds($campaignIds, $adGroupIds, $labelIds)
{
print("-----\r\nGetting Labels by IDs:\r\n");
$paging = (new Paging())
->setIndex(0)
->setSize(self::MAX_GET_LABELS_BY_IDS);
$request = (new GetLabelsByIdsRequest())
->setLabelIds($labelIds)
->setPageInfo($paging);
$response = self::$campaignManagementServiceApi->getLabelsByIds($request);
$retrievedLabels = $response->getLabels();
print_r($retrievedLabels);
self::assertNotEmpty($retrievedLabels);
self::assertEmpty($response->getPartialErrors());
print("-----\nAssociating all of the labels with a campaign...\r\n");
$campaignLabelAssociations = $this->CreateExampleLabelAssociationsByEntityId(
$campaignIds[0],
$labelIds
);
$request = (new SetLabelAssociationsRequest())
->setLabelAssociations($campaignLabelAssociations)
->setEntityType(EntityType::CAMPAIGN);
$response = self::$campaignManagementServiceApi->setLabelAssociations($request);
self::assertEmpty($response->getPartialErrors());
print("-----\nAssociating all of the labels with an ad group...\r\n");
$adGroupLabelAssociations = $this->CreateExampleLabelAssociationsByEntityId(
$adGroupIds[0],
$labelIds
);
$request = (new SetLabelAssociationsRequest())
->setLabelAssociations($adGroupLabelAssociations)
->setEntityType(EntityType::AD_GROUP);
$response = self::$campaignManagementServiceApi->setLabelAssociations($request);
self::assertEmpty($response->getPartialErrors());
print("-----\nUse paging to get all campaign label associations...\r\n");
self::GetLabelAssociationsByLabelIdsHelper(EntityType::CAMPAIGN, $labelIds);
print("-----\nUse paging to get all ad group label associations...\r\n");
self::GetLabelAssociationsByLabelIdsHelper(EntityType::AD_GROUP, $labelIds);
print("-----\nGet all label associations for all specified campaigns...\r\n");
self::GetLabelAssociationsByEntityIdsHelper(
EntityType::CAMPAIGN,
$campaignIds
);
print("-----\nGet all label associations for all specified ad groups...\r\n");
self::GetLabelAssociationsByEntityIdsHelper(
EntityType::AD_GROUP,
$adGroupIds
);
print("-----\nDelete all label associations that we set above....\r\n");
// Deleting the associations is not necessary if you are deleting the corresponding campaign(s), as the
// contained ad groups, ads, and associations would also be deleted.
self::deleteLabelAssociationsRequest(
EntityType::CAMPAIGN,
$campaignLabelAssociations
);
self::deleteLabelAssociationsRequest(
EntityType::AD_GROUP,
$adGroupLabelAssociations
);
return $labelIds;
}
/**
* @depends testGetLabelsByIds
* @throws ApiException
*/
public function testDeleteLabels($labelIds)
{
print("-----\r\nDeleting Labels:\r\n");
$request = (new DeleteLabelsRequest())
->setLabelIds($labelIds);
$response = self::$campaignManagementServiceApi->deleteLabels($request);
printf("Deleted Label ids: %s\r\n", implode(', ', $labelIds));
self::assertEmpty($response->getPartialErrors());
}
/**
* @depends testAddCampaigns
* @depends testDeleteLabels
* @throws ApiException
*/
public function testDeleteCampaigns($campaignIds)
{
self::deleteCampaignsRequest($campaignIds);
}
private function CreateExampleLabelAssociationsByEntityId(
$entityId,
$labelIds
): array {
$labelAssociations = array();
foreach ($labelIds as $labelId) {
$labelAssociation = new LabelAssociation();
$labelAssociation->setEntityId($entityId);
$labelAssociation->setLabelId($labelId);
$labelAssociations[] = $labelAssociation;
}
return $labelAssociations;
}
/**
* @throws ApiException
*/
private function GetLabelAssociationsByLabelIdsHelper(
$entityType,
$labelIds
): void {
$labelAssociations = array();
$labelIdsPageIndex = 0;
while ($labelIdsPageIndex * self::MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < count($labelIds)) {
$getLabelIds = array_slice(
$labelIds,
$labelIdsPageIndex++ * self::MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS,
self::MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS
);
$labelAssociationsPageIndex = 0;
$foundLastPage = false;
while (!$foundLastPage) {
$labelsPaging = new Paging();
$labelsPaging->setIndex($labelAssociationsPageIndex++);
$labelsPaging->setSize(self::MAX_PAGING_SIZE);
$getLabelAssociations = self::getLabelAssociationsByLabelIdsRequest(
$entityType,
$getLabelIds,
$labelsPaging
);
$labelAssociations = array_merge(
$labelAssociations,
$getLabelAssociations
);
$foundLastPage = self::MAX_PAGING_SIZE > count($getLabelAssociations);
}
}
}
/**
* @throws ApiException
*/
private function GetLabelAssociationsByEntityIdsHelper(
$entityType,
$entityIds
): void {
$labelAssociations = array();
$entityIdsPageIndex = 0;
while ($entityIdsPageIndex * self::MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < count($entityIds)) {
$getEntityIds = array_slice(
$entityIds,
$entityIdsPageIndex++ * self::MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS,
self::MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS
);
$getLabelAssociationsByEntityIds = self::getLabelAssociationsByEntityIdsRequest(
$entityType,
$getEntityIds
);
$labelAssociations = array_merge(
$labelAssociations,
$getLabelAssociationsByEntityIds
);
}
}
}
import uuid
import random
from auth_helper import *
from openapi_client.models.campaign import *
# Constants for pagination
MAX_GET_LABELS_BY_IDS = 1000
MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS = 1
MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS = 100
MAX_PAGING_SIZE = 1000
def create_label_associations_by_entity_id(entity_id, label_ids):
"""
Create label associations for a given entity ID and label IDs.
Args:
entity_id: The entity ID (campaign or ad group)
label_ids: List of label IDs to associate
Returns:
List of LabelAssociation objects
"""
label_associations = []
for label_id in label_ids:
association = LabelAssociation(
entity_id=entity_id,
label_id=label_id
)
label_associations.append(association)
return label_associations
def get_label_associations_by_label_ids_helper(campaign_service, entity_type, label_ids):
"""
Get all label associations by label IDs with pagination.
Args:
campaign_service: The campaign service client
entity_type: The entity type (Campaign or AdGroup)
label_ids: List of label IDs
"""
print(f"Getting label associations by label IDs for {entity_type}...")
label_associations = []
label_ids_page_index = 0
while label_ids_page_index * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS < len(label_ids):
get_label_ids = label_ids[
label_ids_page_index * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS:
(label_ids_page_index + 1) * MAX_LABEL_IDS_FOR_GET_LABEL_ASSOCIATIONS
]
label_ids_page_index += 1
label_associations_page_index = 0
found_last_page = False
while not found_last_page:
paging = Paging(
index=label_associations_page_index,
size=MAX_PAGING_SIZE
)
label_associations_page_index += 1
get_associations_request = GetLabelAssociationsByLabelIdsRequest(
entity_type=entity_type,
label_ids=get_label_ids,
page_info=paging
)
get_associations_response = campaign_service.get_label_associations_by_label_ids(
get_label_associations_by_label_ids_request=get_associations_request
)
associations = get_associations_response.LabelAssociations
if associations:
label_associations.extend(associations)
found_last_page = len(associations) < MAX_PAGING_SIZE
else:
found_last_page = True
print(f" Found {len(label_associations)} label associations")
def get_label_associations_by_entity_ids_helper(campaign_service, entity_type, entity_ids):
"""
Get all label associations by entity IDs with pagination.
Args:
campaign_service: The campaign service client
entity_type: The entity type (Campaign or AdGroup)
entity_ids: List of entity IDs
"""
print(f"Getting label associations by entity IDs for {entity_type}...")
label_associations = []
entity_ids_page_index = 0
while entity_ids_page_index * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS < len(entity_ids):
get_entity_ids = entity_ids[
entity_ids_page_index * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS:
(entity_ids_page_index + 1) * MAX_ENTITY_IDS_FOR_GET_LABEL_ASSOCIATIONS
]
entity_ids_page_index += 1
get_associations_request = GetLabelAssociationsByEntityIdsRequest(
entity_type=entity_type,
entity_ids=get_entity_ids
)
get_associations_response = campaign_service.get_label_associations_by_entity_ids(
get_label_associations_by_entity_ids_request=get_associations_request
)
associations = get_associations_response.LabelAssociations
if associations:
label_associations.extend(associations)
print(f" Found {len(label_associations)} label associations")
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]}")
# Create an ad group
print("\nCreating ad group...")
current_year = datetime.now().year
ad_group = AdGroup(
name="Ad Group Women's Red Shoe Sale" + str(uuid.uuid4())[:8],
cpc_bid=Bid(amount=0.09),
end_date=Date(day=31, month=12, year=current_year)
)
add_ad_groups_request = AddAdGroupsRequest(
campaign_id=campaign_ids[0],
ad_groups=[ad_group]
)
add_ad_groups_response = campaign_service.add_ad_groups(
add_ad_groups_request=add_ad_groups_request
)
ad_group_ids = add_ad_groups_response.AdGroupIds
print(f"Created Ad Group ID: {ad_group_ids[0]}")
# Create labels
print("\nCreating labels...")
labels = []
for i in range(5):
# Generate random color code
color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
label = Label(
color_code=color,
description='Label Description',
name=f'Label Name {color} {str(uuid.uuid4())[:8]}'
)
labels.append(label)
add_labels_request = AddLabelsRequest(
labels=labels
)
add_labels_response = campaign_service.add_labels(
add_labels_request=add_labels_request
)
label_ids = add_labels_response.LabelIds
print(f"Created Label IDs: {label_ids}")
if add_labels_response.PartialErrors:
print(f"Partial Errors: {add_labels_response.PartialErrors}")
# Get labels by IDs
print("\nGetting labels by IDs...")
paging = Paging(
index=0,
size=MAX_GET_LABELS_BY_IDS
)
get_labels_request = GetLabelsByIdsRequest(
label_ids=label_ids,
page_info=paging
)
get_labels_response = campaign_service.get_labels_by_ids(
get_labels_by_ids_request=get_labels_request
)
retrieved_labels = get_labels_response.Labels
print(f"Retrieved {len(retrieved_labels)} labels")
# Associate labels with campaign
print("\nAssociating all labels with campaign...")
campaign_label_associations = create_label_associations_by_entity_id(
campaign_ids[0],
label_ids
)
set_campaign_associations_request = SetLabelAssociationsRequest(
entity_type=EntityType.CAMPAIGN,
label_associations=campaign_label_associations
)
set_campaign_associations_response = campaign_service.set_label_associations(
set_label_associations_request=set_campaign_associations_request
)
if set_campaign_associations_response.PartialErrors:
print(f"Partial Errors: {set_campaign_associations_response.PartialErrors}")
else:
print("Campaign label associations set successfully")
# Associate labels with ad group
print("\nAssociating all labels with ad group...")
ad_group_label_associations = create_label_associations_by_entity_id(
ad_group_ids[0],
label_ids
)
set_ad_group_associations_request = SetLabelAssociationsRequest(
entity_type=EntityType.ADGROUP,
label_associations=ad_group_label_associations
)
set_ad_group_associations_response = campaign_service.set_label_associations(
set_label_associations_request=set_ad_group_associations_request
)
if set_ad_group_associations_response.PartialErrors:
print(f"Partial Errors: {set_ad_group_associations_response.PartialErrors}")
else:
print("Ad group label associations set successfully")
# Get label associations by label IDs for campaigns
print("\nGetting campaign label associations by label IDs (with paging)...")
get_label_associations_by_label_ids_helper(
campaign_service,
EntityType.CAMPAIGN,
label_ids
)
# Get label associations by label IDs for ad groups
print("\nGetting ad group label associations by label IDs (with paging)...")
get_label_associations_by_label_ids_helper(
campaign_service,
EntityType.ADGROUP,
label_ids
)
# Get label associations by entity IDs for campaigns
print("\nGetting label associations by campaign entity IDs...")
get_label_associations_by_entity_ids_helper(
campaign_service,
EntityType.CAMPAIGN,
campaign_ids
)
# Get label associations by entity IDs for ad groups
print("\nGetting label associations by ad group entity IDs...")
get_label_associations_by_entity_ids_helper(
campaign_service,
EntityType.ADGROUP,
ad_group_ids
)
# Delete label associations
print("\nDeleting label associations...")
# Delete campaign label associations
delete_campaign_associations_request = DeleteLabelAssociationsRequest(
entity_type=EntityType.CAMPAIGN,
label_associations=campaign_label_associations
)
delete_campaign_associations_response = campaign_service.delete_label_associations(
delete_label_associations_request=delete_campaign_associations_request
)
if delete_campaign_associations_response.PartialErrors:
print(f"Campaign Partial Errors: {delete_campaign_associations_response.PartialErrors}")
else:
print("Campaign label associations deleted successfully")
# Delete ad group label associations
delete_ad_group_associations_request = DeleteLabelAssociationsRequest(
entity_type=EntityType.ADGROUP,
label_associations=ad_group_label_associations
)
delete_ad_group_associations_response = campaign_service.delete_label_associations(
delete_label_associations_request=delete_ad_group_associations_request
)
if delete_ad_group_associations_response.PartialErrors:
print(f"Ad Group Partial Errors: {delete_ad_group_associations_response.PartialErrors}")
else:
print("Ad group label associations deleted successfully")
# Delete labels
print("\nDeleting labels...")
delete_labels_request = DeleteLabelsRequest(
label_ids=label_ids
)
delete_labels_response = campaign_service.delete_labels(
delete_labels_request=delete_labels_request
)
if delete_labels_response.PartialErrors:
print(f"Partial Errors: {delete_labels_response.PartialErrors}")
else:
print(f"Deleted Label IDs: {label_ids}")
# Delete campaign
print("\nDeleting campaign...")
delete_campaigns_request = DeleteCampaignsRequest(
account_id=authorization_data.account_id,
campaign_ids=campaign_ids
)
campaign_service.delete_campaigns(
delete_campaigns_request=delete_campaigns_request
)
print(f"Deleted Campaign ID {campaign_ids[0]}")
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)
campaign_service = ServiceClient(
service='CampaignManagementService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
main(authorization_data)