-
Notifications
You must be signed in to change notification settings - Fork 96
/
SetUpRemarketing.cs
494 lines (444 loc) · 24 KB
/
SetUpRemarketing.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.Gax.Util;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V16.Common;
using Google.Ads.GoogleAds.V16.Errors;
using Google.Ads.GoogleAds.V16.Resources;
using Google.Ads.GoogleAds.V16.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V16.Enums.UserListMembershipStatusEnum.Types;
using static Google.Ads.GoogleAds.V16.Enums.UserListPrepopulationStatusEnum.Types;
using static Google.Ads.GoogleAds.V16.Enums.UserListStringRuleItemOperatorEnum.Types;
using static Google.Ads.GoogleAds.V16.Errors.CriterionErrorEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V16
{
/// <summary>
/// Demonstrates various operations involved in remarketing, including:
/// (a) creating a user list based on visitors to a website,
/// (b) targeting a user list with an ad group criterion,
/// (c) updating the bid modifier on an ad group criterion,
/// (d) finding and removing all ad group criteria under a given campaign,
/// (e) targeting a user list with a campaign criterion, and
/// (f) updating the bid modifier on a campaign criterion.
/// It is unlikely that users will need to perform all of these operations consecutively, and
/// all of the operations contained herein are meant of for illustrative purposes.
/// Note: you can use user lists to target at the campaign or ad group level, but not both
/// simultaneously. Consider removing or disabling any existing user lists at the campaign level
/// before running this example.
/// </summary>
public class SetUpRemarketing : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="SetUpRemarketing"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// The ad group ID on which criteria will be targeted.
/// </summary>
[Option("adGroupId", Required = true, HelpText =
"The ad group ID on which criteria will be targeted.")]
public long AdGroupId { get; set; }
/// <summary>
/// The campaign ID on which criteria will be targeted.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"The campaign ID on which criteria will be targeted.")]
public long CampaignId { get; set; }
/// <summary>
/// The bid modifier value.
/// </summary>
[Option("bidModifierValue", Required = true, HelpText =
"The bid modifier value.")]
public double BidModifierValue { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(args);
SetUpRemarketing codeExample = new SetUpRemarketing();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.AdGroupId,
options.CampaignId, options.BidModifierValue);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"Demonstrates various operations involved in remarketing, including:\n" +
"\t(a) creating a user list based on visitors to a website,\n" +
"\t(b) targeting a user list with an ad group criterion,\n" +
"\t(c) updating the bid modifier on an ad group criterion,\n" +
"\t(d) finding and removing all ad group criteria under a given campaign,\n" +
"\t(e) targeting a user list with a campaign criterion, and\n" +
"\t(f) updating the bid modifier on a campaign criterion.\n" +
"It is unlikely that users will need to perform all of these operations " +
"consecutively, and all of the operations contained herein are meant of for " +
"illustrative purposes.\n" +
"Note: you can use user lists to target at the campaign or ad group level, but not " +
"both simultaneously. Consider removing or disabling any existing user lists at the " +
"campaign level before running this example.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupId">The ad group ID on which criteria will be targeted.</param>
/// <param name="campaignId">The campaign ID on which criteria will be targeted.</param>
/// <param name="bidModifierValue">The bid modifier value.</param>
public void Run(GoogleAdsClient client, long customerId, long adGroupId, long campaignId,
double bidModifierValue)
{
try
{
// Create a new example user list.
string userListResourceName = CreateUserList(client, customerId);
// Target an ad group to the new user list.
string adGroupCriterionResourceName =
TargetAdsInAdGroupToUserList(client, customerId, adGroupId,
userListResourceName);
ModifyAdGroupBids(client, customerId, adGroupCriterionResourceName,
bidModifierValue);
// Remove any existing user lists at the ad group level.
RemoveExistingListCriteriaFromAdGroup(client, customerId, campaignId);
// Target the campaign to the new user list.
string campaignCriterionResourceName =
TargetAdsInCampaignToUserList(client, customerId, campaignId,
userListResourceName);
ModifyCampaignBids(client, customerId, campaignCriterionResourceName,
bidModifierValue);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
if (e.Failure.Errors.First().ErrorCode.CriterionError ==
CriterionError.CannotAttachCriteriaAtCampaignAndAdgroup)
{
Console.WriteLine("This error can occur when user lists are already targeted " +
"at the campaign level. You can use user lists to target at the campaign " +
"or ad group level, but not both simultaneously. Consider removing or " +
"disabling any existing user lists at the campaign level before running " +
"this example.");
}
throw;
}
}
/// <summary>
/// Creates a user list targeting users that have visited a given url.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <returns>The resource name of the newly created user list.</returns>
// [START setup_remarketing]
private string CreateUserList(GoogleAdsClient client, long customerId)
{
// Get the UserListService client.
UserListServiceClient userListServiceClient =
client.GetService(Services.V16.UserListService);
// Create a rule targeting any user that visited a url containing 'example.com'.
UserListRuleItemInfo rule = new UserListRuleItemInfo
{
// Use a built-in parameter to create a domain URL rule.
Name = "url__",
StringRuleItem = new UserListStringRuleItemInfo
{
Operator = UserListStringRuleItemOperator.Contains,
Value = "example.com"
}
};
// Specify that the user list targets visitors of a page based on the provided rule.
FlexibleRuleUserListInfo flexibleRuleUserListInfo = new FlexibleRuleUserListInfo();
FlexibleRuleOperandInfo flexibleRuleOperandInfo = new FlexibleRuleOperandInfo() {
Rule = new UserListRuleInfo()
};
UserListRuleItemGroupInfo userListRuleItemGroupInfo = new UserListRuleItemGroupInfo();
userListRuleItemGroupInfo.RuleItems.Add(rule);
flexibleRuleOperandInfo.Rule.RuleItemGroups.Add(userListRuleItemGroupInfo);
flexibleRuleUserListInfo.InclusiveOperands.Add(flexibleRuleOperandInfo);
// Define a representation of a user list that is generated by a rule.
RuleBasedUserListInfo ruleBasedUserListInfo = new RuleBasedUserListInfo
{
// Optional: To include past users in the user list, set the prepopulation_status to
// REQUESTED.
PrepopulationStatus = UserListPrepopulationStatus.Requested,
FlexibleRuleUserList = flexibleRuleUserListInfo
};
// Create the user list.
UserList userList = new UserList
{
Name = $"All visitors to example.com #{ExampleUtilities.GetRandomString()}",
Description = "Any visitor to any page of example.com",
MembershipStatus = UserListMembershipStatus.Open,
MembershipLifeSpan = 365L,
RuleBasedUserList = ruleBasedUserListInfo
};
// Create the operation.
UserListOperation userListOperation = new UserListOperation
{
Create = userList
};
// Add the user list, then print and return the new list's resource name.
MutateUserListsResponse mutateUserListsResponse = userListServiceClient
.MutateUserLists(customerId.ToString(), new[] { userListOperation });
string userListResourceName = mutateUserListsResponse.Results.First().ResourceName;
Console.WriteLine($"Created user list with resource name '{userListResourceName}'.");
return userListResourceName;
}
// [END setup_remarketing]
/// <summary>
/// Creates an ad group criterion that targets a user list with an ad group.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupId">The ad group on which the user list will be targeted.</param>
/// <param name="userListResourceName">The resource name of the user list to be
/// targeted.</param>
/// <returns>The resource name of the newly created ad group criterion.</returns>
// [START setup_remarketing_1]
private string TargetAdsInAdGroupToUserList(
GoogleAdsClient client, long customerId, long adGroupId, string userListResourceName)
{
// Get the AdGroupCriterionService client.
AdGroupCriterionServiceClient adGroupCriterionServiceClient = client.GetService
(Services.V16.AdGroupCriterionService);
// Create the ad group criterion targeting members of the user list.
AdGroupCriterion adGroupCriterion = new AdGroupCriterion
{
AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
UserList = new UserListInfo
{
UserList = userListResourceName
}
};
// Create the operation.
AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
{
Create = adGroupCriterion
};
// Add the ad group criterion, then print and return the new criterion's resource name.
MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
new[] { adGroupCriterionOperation });
string adGroupCriterionResourceName =
mutateAdGroupCriteriaResponse.Results.First().ResourceName;
Console.WriteLine("Successfully created ad group criterion with resource name " +
$"'{adGroupCriterionResourceName}' targeting user list with resource name " +
$"'{userListResourceName}' with ad group with ID {adGroupId}.");
return adGroupCriterionResourceName;
}
// [END setup_remarketing_1]
/// <summary>
/// Updates the bid modifier on an ad group criterion.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupCriterionResourceName">The resource name of the ad group criterion to update.</param>
/// <param name="bidModifierValue">The bid modifier value.</param>
private void ModifyAdGroupBids(
GoogleAdsClient client,
long customerId,
string adGroupCriterionResourceName,
double bidModifierValue)
{
// Get the AdGroupCriterionService client.
AdGroupCriterionServiceClient adGroupCriterionServiceClient =
client.GetService(Services.V16.AdGroupCriterionService);
// Create the ad group criterion with a bid modifier. You may alternatively set the bid
// for the ad group criterion directly.
AdGroupCriterion adGroupCriterion = new AdGroupCriterion
{
ResourceName = adGroupCriterionResourceName,
BidModifier = bidModifierValue
};
// Create the update operation.
AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation
{
Update = adGroupCriterion,
UpdateMask = FieldMasks.AllSetFieldsOf(adGroupCriterion)
};
// Update the ad group criterion and print the results.
MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
new[] { adGroupCriterionOperation });
Console.WriteLine("Successfully updated the bid for ad group criterion with resource " +
$"name '{mutateAdGroupCriteriaResponse.Results.First().ResourceName}'.");
}
/// <summary>
/// Removes all ad group criteria targeting a user list under a given campaign. This is a
/// necessary step before targeting a user list at the campaign level.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">The campaign from which to remove the ad group criteria.</param>
// [START setup_remarketing_3]
private void RemoveExistingListCriteriaFromAdGroup(GoogleAdsClient client, long customerId,
long campaignId)
{
// Get the AdGroupCriterionService client.
AdGroupCriterionServiceClient adGroupCriterionServiceClient =
client.GetService(Services.V16.AdGroupCriterionService);
// Retrieve all of the ad group criteria under a campaign.
List<string> adGroupCriteria =
GetUserListAdGroupCriteria(client, customerId, campaignId);
// Create a list of remove operations.
List<AdGroupCriterionOperation> operations = adGroupCriteria.Select(adGroupCriterion =>
new AdGroupCriterionOperation { Remove = adGroupCriterion }).ToList();
// Remove the ad group criteria and print the resource names of the removed criteria.
MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
adGroupCriterionServiceClient.MutateAdGroupCriteria(customerId.ToString(),
operations);
Console.WriteLine($"Removed {mutateAdGroupCriteriaResponse.Results.Count} ad group " +
"criteria.");
foreach (MutateAdGroupCriterionResult result in mutateAdGroupCriteriaResponse.Results)
{
Console.WriteLine("Successfully removed ad group criterion with resource name " +
$"'{result.ResourceName}'.");
}
}
// [END setup_remarketing_3]
/// <summary>
/// Finds all of user list ad group criteria under a campaign.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">The campaign in which to search the ad group criteria.</param>
/// <returns>A list of ad group criteria resource names.</returns>
// [START setup_remarketing_2]
private List<string> GetUserListAdGroupCriteria(
GoogleAdsClient client, long customerId, long campaignId)
{
// Get the GoogleAdsService client.
GoogleAdsServiceClient googleAdsServiceClient =
client.GetService(Services.V16.GoogleAdsService);
List<string> userListCriteriaResourceNames = new List<string>();
// Create a query that will retrieve all of the ad group criteria under a campaign.
string query = $@"
SELECT ad_group_criterion.criterion_id
FROM ad_group_criterion
WHERE
campaign.id = {campaignId}
AND ad_group_criterion.type = 'USER_LIST'";
// Issue the search request.
googleAdsServiceClient.SearchStream(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse resp)
{
// Display the results and add the resource names to the list.
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
string adGroupCriterionResourceName =
googleAdsRow.AdGroupCriterion.ResourceName;
Console.WriteLine("Ad group criterion with resource name " +
$"{adGroupCriterionResourceName} was found.");
userListCriteriaResourceNames.Add(adGroupCriterionResourceName);
}
});
return userListCriteriaResourceNames;
}
// [END setup_remarketing_2]
/// <summary>
/// Creates a campaign criterion that targets a user list with a campaign.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignId">The campaign on which the user list will be targeted.</param>
/// <param name="userListResourceName">The resource name of the user list to be
/// targeted.</param>
/// <returns>The resource name of the newly created campaign criterion.</returns>
// [START setup_remarketing_4]
private string TargetAdsInCampaignToUserList(
GoogleAdsClient client, long customerId, long campaignId, string userListResourceName)
{
// Get the CampaignCriterionService client.
CampaignCriterionServiceClient campaignCriterionServiceClient =
client.GetService(Services.V16.CampaignCriterionService);
// Create the campaign criterion.
CampaignCriterion campaignCriterion = new CampaignCriterion
{
Campaign = ResourceNames.Campaign(customerId, campaignId),
UserList = new UserListInfo
{
UserList = userListResourceName
}
};
// Create the operation.
CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
{
Create = campaignCriterion
};
// Add the campaign criterion and print the resulting criterion's resource name.
MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
new[] { campaignCriterionOperation });
string campaignCriterionResourceName =
mutateCampaignCriteriaResponse.Results.First().ResourceName;
Console.WriteLine("Successfully created campaign criterion with resource name " +
$"'{campaignCriterionResourceName}' targeting user list with resource name " +
$"'{userListResourceName}' with campaign with ID {campaignId}.");
return campaignCriterionResourceName;
}
// [END setup_remarketing_4]
/// <summary>
/// Updates the bid modifier on a campaign criterion.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="campaignCriterionResourceName">The resource name of the campaign criterion to update.</param>
/// <param name="bidModifierValue">The bid modifier value.</param>
private void ModifyCampaignBids(
GoogleAdsClient client,
long customerId,
string campaignCriterionResourceName,
double bidModifierValue)
{
// Get the CampaignCriterionService client.
CampaignCriterionServiceClient campaignCriterionServiceClient =
client.GetService(Services.V16.CampaignCriterionService);
// Create the campaign criterion to update.
CampaignCriterion campaignCriterion = new CampaignCriterion
{
ResourceName = campaignCriterionResourceName,
BidModifier = (float) bidModifierValue
};
// Create the update operation.
CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
{
Update = campaignCriterion,
UpdateMask = FieldMasks.AllSetFieldsOf(campaignCriterion)
};
// Update the campaign criterion and print the results.
MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
new[] { campaignCriterionOperation });
Console.WriteLine("Successfully updated the bid for campaign criterion with resource " +
$"name '{mutateCampaignCriteriaResponse.Results.First().CampaignCriterion}'.");
}
}
}