-
Notifications
You must be signed in to change notification settings - Fork 95
/
AddDynamicPageFeed.cs
507 lines (444 loc) · 20.3 KB
/
AddDynamicPageFeed.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
495
496
497
498
499
500
501
502
503
504
505
506
507
// Copyright 2019 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.V11.Common;
using Google.Ads.GoogleAds.V11.Errors;
using Google.Ads.GoogleAds.V11.Resources;
using Google.Ads.GoogleAds.V11.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V11.Enums.DsaPageFeedCriterionFieldEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.FeedAttributeTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.FeedMappingCriterionTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.WebpageConditionOperandEnum.Types;
using static Google.Ads.GoogleAds.V11.Resources.Campaign.Types;
namespace Google.Ads.GoogleAds.Examples.V11
{
/// <summary>
/// This code example adds a page feed to specify precisely which URLs to use with your
/// Dynamic Search Ads.
/// </summary>
[Obsolete("Feed-services based DSA page feeds are deprecated and being replaced with " +
"assets. See AddDynamicPageFeedAsset.cs.")]
public class AddDynamicPageFeed : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddDynamicPageFeed"/> 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>
/// ID of the campaign for which dynamic page feeds are added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"ID of the campaign for which dynamic page feeds are added.")]
public long CampaignId { get; set; }
/// <summary>
/// ID of the ad group for which dynamic page feeds are added.
/// </summary>
[Option("adGroupId", Required = true, HelpText =
"ID of the ad group for which dynamic page feeds are added.")]
public long AdGroupId { 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);
AddDynamicPageFeed codeExample = new AddDynamicPageFeed();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId,
options.AdGroupId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example adds a page feed to specify precisely which URLs to use with " +
"your Dynamic Search Ads.";
/// <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="campaignId">ID of the campaign for which dynamic page feeds are added.
/// </param>
/// <param name="adGroupId">ID of the ad group for which dynamic page feeds are added.
/// </param>
public void Run(GoogleAdsClient client, long customerId, long campaignId, long adGroupId)
{
try
{
string dsaPageUrlLabel = "discounts";
// Get the page feed details. This code example creates a new feed, but you can
// fetch and re-use an existing feed.
string feedResourceName = CreateFeed(client, customerId);
Dictionary<DsaPageFeedCriterionField, FeedAttribute> feedAttributes =
GetFeed(client, customerId, feedResourceName);
CreateFeedMapping(client, customerId, feedResourceName, feedAttributes);
CreateFeedItems(client, customerId, feedResourceName, feedAttributes,
dsaPageUrlLabel);
// Associates the page feed with the campaign.
UpdateCampaignDsaSetting(client, customerId, feedResourceName, campaignId);
// Optional: Targets web pages matching the feed's label in the ad group.
AddDsaTarget(client, customerId, adGroupId, dsaPageUrlLabel);
Console.WriteLine($"Dynamic page feed setup is complete for campaign " +
$"ID {campaignId}");
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the feed.
/// </summary>
/// <param name="client">The Google Ads 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 feed.</returns>
private string CreateFeed(GoogleAdsClient client, long customerId)
{
// Get the FeedService.
FeedServiceClient feedService = client.GetService(Services.V11.FeedService);
// Create a URL attribute.
FeedAttribute urlAttribute = new FeedAttribute()
{
Type = FeedAttributeType.UrlList,
Name = "Page URL"
};
// Create a label attribute.
FeedAttribute labelAttribute = new FeedAttribute()
{
Type = FeedAttributeType.StringList,
Name = "Label"
};
// Create the feed.
Feed feed = new Feed()
{
Name = "DSA Feed #" + ExampleUtilities.GetRandomString(),
Attributes = { urlAttribute, labelAttribute }
};
// Create the operation.
FeedOperation operation = new FeedOperation()
{
Create = feed
};
// Add the feed.
MutateFeedsResponse response =
feedService.MutateFeeds(customerId.ToString(), new[] { operation });
string feedResourceName = response.Results[0].ResourceName;
// Display the result.
Console.WriteLine($"Feed with resource name '{feedResourceName}' was created.");
return feedResourceName;
}
/// <summary>
/// Retrieves details about a feed.
/// </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="feedResourceName">The feed resource name.</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private Dictionary<DsaPageFeedCriterionField, FeedAttribute> GetFeed(
GoogleAdsClient client, long customerId, string feedResourceName)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V11.GoogleAdsService);
// Construct the query.
String query = $"SELECT feed.attributes FROM feed WHERE feed.resource_name" +
$" = '{feedResourceName}'";
// Construct the request.
SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
{
CustomerId = customerId.ToString(),
Query = query
};
// Issue the search request.
Feed feed = googleAdsService.Search(customerId.ToString(), query).First().Feed;
Dictionary<DsaPageFeedCriterionField, FeedAttribute> retval =
new Dictionary<DsaPageFeedCriterionField, FeedAttribute>();
foreach (FeedAttribute attribute in feed.Attributes)
{
DsaPageFeedCriterionField key;
switch (attribute.Name)
{
case "Page URL":
key = DsaPageFeedCriterionField.PageUrl;
break;
case "Label":
key = DsaPageFeedCriterionField.Label;
break;
default:
throw new Exception("Unable to map attribute name to DSA page feed" +
" criterion.");
}
retval[key] = attribute;
}
return retval;
}
/// <summary>
/// Creates a feed mapping for a given feed.
/// </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="feedResourceName">The feed resource for which feed mapping is created.
/// </param>
/// <param name="feedAttributes">The feed attributes.</param>
private void CreateFeedMapping(GoogleAdsClient client, long customerId,
string feedResourceName,
Dictionary<DsaPageFeedCriterionField, FeedAttribute> feedAttributes)
{
// Get the FeedMappingService.
FeedMappingServiceClient feedMappingService = client.GetService(
Services.V11.FeedMappingService);
FeedMapping feedMapping = new FeedMapping()
{
CriterionType = FeedMappingCriterionType.DsaPageFeed,
Feed = feedResourceName,
// Map the FeedAttributeId to the fieldId constants.
AttributeFieldMappings =
{
new AttributeFieldMapping()
{
FeedAttributeId = feedAttributes[DsaPageFeedCriterionField.PageUrl].Id,
DsaPageFeedField = DsaPageFeedCriterionField.PageUrl
},
new AttributeFieldMapping()
{
FeedAttributeId = feedAttributes[DsaPageFeedCriterionField.Label].Id,
DsaPageFeedField = DsaPageFeedCriterionField.Label
}
}
};
// Create the operation.
FeedMappingOperation operation = new FeedMappingOperation()
{
Create = feedMapping
};
// Add the FeedMapping.
MutateFeedMappingsResponse response =
feedMappingService.MutateFeedMappings(customerId.ToString(), new[] { operation });
// Display the results.
foreach (MutateFeedMappingResult result in response.Results)
{
Console.WriteLine($"Created feed mapping with resource name" +
$" '{result.ResourceName}'");
}
}
/// <summary>
/// Creates feed items for a given feed.
/// </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="feedResourceName">The feed resource for which feed items are created.
/// </param>
/// <param name="feedAttributes">The feed attributes.</param>
/// <param name="dsaPageUrlLabel">The DSA page URL label.</param>
private void CreateFeedItems(GoogleAdsClient client, long customerId,
string feedResourceName,
Dictionary<DsaPageFeedCriterionField, FeedAttribute> feedAttributes,
string dsaPageUrlLabel)
{
// Get the FeedItemService.
FeedItemServiceClient feedItemService = client.GetService(
Services.V11.FeedItemService);
List<string> urls = new List<string>
{
"http://www.example.com/discounts/rental-cars",
"http://www.example.com/discounts/hotel-deals",
"http://www.example.com/discounts/flight-deals"
};
List<FeedItemOperation> operations = new List<FeedItemOperation>();
foreach (string url in urls)
{
// Create a feed item.
FeedItem feedItem = new FeedItem()
{
Feed = feedResourceName,
AttributeValues =
{
// Create a url attribute.
new FeedItemAttributeValue()
{
FeedAttributeId = feedAttributes[DsaPageFeedCriterionField.PageUrl].Id,
StringValue = url
},
// Creates a label attribute.
new FeedItemAttributeValue()
{
FeedAttributeId = feedAttributes[DsaPageFeedCriterionField.Label].Id,
StringValue = dsaPageUrlLabel
}
}
};
operations.Add(new FeedItemOperation()
{
Create = feedItem
});
}
// Add the feed items.
MutateFeedItemsResponse response =
feedItemService.MutateFeedItems(customerId.ToString(), operations);
// Display the results.
foreach (MutateFeedItemResult result in response.Results)
{
Console.WriteLine($"Created feed items with resource " +
$"name '{result.ResourceName}'.");
}
}
/// <summary>
/// Updates a campaign to set the DSA feed.
/// </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="feedResourceName">The DSA feed resource name</param>
/// <param name="campaignId">ID of the campaign for which DSA settings are updated.</param>
// [START add_dynamic_page_feed_1]
private void UpdateCampaignDsaSetting(GoogleAdsClient client, long customerId,
string feedResourceName, long campaignId)
{
// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(
Services.V11.CampaignService);
DynamicSearchAdsSetting dsaSetting = GetDsaSetting(client, customerId, campaignId);
dsaSetting.Feeds.Add(feedResourceName);
// Create the campaign.
Campaign campaign = new Campaign()
{
ResourceName = ResourceNames.Campaign(customerId, campaignId),
DynamicSearchAdsSetting = dsaSetting
};
// Create the operation.
CampaignOperation operation = new CampaignOperation()
{
Update = campaign,
UpdateMask = FieldMasks.AllSetFieldsOf(campaign)
};
// Update the campaign.
MutateCampaignsResponse response =
campaignService.MutateCampaigns(customerId.ToString(), new[] { operation });
// Display the results.
foreach (MutateCampaignResult mutateCampaignResult in response.Results)
{
Console.WriteLine($"Updated campaign with resourceName: " +
$"'{mutateCampaignResult.ResourceName}'.");
}
}
// [END add_dynamic_page_feed_1]
/// <summary>
/// Returns the DSA settings for a campaign. Throws an error if the campaign does not
/// exist or is not a DSA campaign.
/// </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="campaignId">ID of the campaign for which DSA settings are fetched.</param>
/// <returns>The DSA settings.</returns>
// [START add_dynamic_page_feed]
private DynamicSearchAdsSetting GetDsaSetting(GoogleAdsClient client, long customerId,
long campaignId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V11.GoogleAdsService);
// Creates the query.
// You must request all DSA fields in order to update the DSA settings in the
// following step.
string query =
$@"SELECT
campaign.id,
campaign.name,
campaign.dynamic_search_ads_setting.use_supplied_urls_only
FROM
campaign
WHERE
campaign.id = {campaignId}";
GoogleAdsRow result = googleAdsService.Search(
customerId.ToString(), query).FirstOrDefault();
if (result == null)
{
throw new Exception("No campaign found with ID: " + campaignId);
}
// Gets the DSA settings.
DynamicSearchAdsSetting dynamicSearchAdsSetting =
result.Campaign.DynamicSearchAdsSetting;
// Throws an exception if the campaign is not a DSA campaign.
if (dynamicSearchAdsSetting == null)
{
throw new Exception($"Campaign with ID {campaignId} is not a DSA campaign.");
}
return dynamicSearchAdsSetting;
}
// [END add_dynamic_page_feed]
// [START add_dynamic_page_feed_2]
private void AddDsaTarget(GoogleAdsClient client, long customerId, long adGroupId,
string dsaPageUrlLabel)
{
// Get the AdGroupCriterionService.
AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(
Services.V11.AdGroupCriterionService);
// Create the webpage condition info.
WebpageConditionInfo webpageConditionInfo = new WebpageConditionInfo()
{
Operand = WebpageConditionOperand.CustomLabel,
Argument = dsaPageUrlLabel,
};
// Creates the webpage info.
WebpageInfo webpageInfo = new WebpageInfo()
{
CriterionName = "Test Criterion",
Conditions = { webpageConditionInfo }
};
// Creates the ad group criterion.
AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
{
AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
Webpage = webpageInfo,
CpcBidMicros = 1_500_000
};
// Create the operation.
AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
{
Create = adGroupCriterion
};
// Add the ad group criterion.
MutateAdGroupCriteriaResponse mutateAdGroupCriteriaResponse =
adGroupCriterionService.MutateAdGroupCriteria(customerId.ToString(),
new[] { operation });
// Display the results.
foreach (MutateAdGroupCriterionResult result in mutateAdGroupCriteriaResponse.Results)
{
Console.WriteLine($"Created ad group criterion with resource name " +
$"'{result.ResourceName}'.");
}
}
// [END add_dynamic_page_feed_2]
}
}