/
AddDynamicPageFeed.cs
executable file
·509 lines (453 loc) · 18.9 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
508
509
// Copyright 2018 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 Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201809;
using System;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code example adds a page feed to specify precisely which URLs to use with your
/// Dynamic Search Ads campaign. To create a Dynamic Search Ads campaign, run
/// AddDynamicSearchAdsCampaign.cs. To get campaigns, run GetCampaigns.cs.
/// </summary>
public class AddDynamicPageFeed : ExampleBase
{
/// <summary>
/// The criterion type to be used for DSA page feeds.
/// </summary>
/// <remarks>DSA page feeds use criterionType field instead of the placeholderType field
/// unlike most other feed types.</remarks>
private const int DSA_PAGE_FEED_CRITERION_TYPE = 61;
/// <summary>
/// ID that corresponds to the page URLs.
/// </summary>
private const int DSA_PAGE_URLS_FIELD_ID = 1;
/// <summary>
/// ID that corresponds to the labels.
/// </summary>
private const int DSA_LABEL_FIELD_ID = 2;
/// <summary>
/// Class to keep track of DSA page feed details.
/// </summary>
private class DSAFeedDetails
{
public long feedId { get; set; }
public long urlAttributeId { get; set; }
public long labelAttributeId { 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)
{
AddDynamicPageFeed codeExample = new AddDynamicPageFeed();
Console.WriteLine(codeExample.Description);
try
{
long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
codeExample.Run(new AdWordsUser(), campaignId, adGroupId);
}
catch (Exception e)
{
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return "This code example adds a page feed to specify precisely which URLs to " +
"use with your Dynamic Search Ads campaign. To create a Dynamic Search Ads " +
"campaign, run AddDynamicSearchAdsCampaign.cs. To get campaigns, " +
"run GetCampaigns.cs.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">The DSA campaign ID.</param>
/// <param name="adGroupId">The DSA ad group ID.</param>
public void Run(AdWordsUser user, long campaignId, long adGroupId)
{
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.
DSAFeedDetails feedDetails = CreateFeed(user);
CreateFeedMapping(user, feedDetails);
CreateFeedItems(user, feedDetails, dsaPageUrlLabel);
// Associate the page feed with the campaign.
UpdateCampaignDsaSetting(user, campaignId, feedDetails.feedId);
// Optional: Target web pages matching the feed's label in the ad group.
AddDsaTargeting(user, adGroupId, dsaPageUrlLabel);
Console.WriteLine("Dynamic page feed setup is complete for campaign ID '{0}'.",
campaignId);
}
/// <summary>
/// Creates the feed for DSA page URLs.
/// </summary>
/// <param name="user">The AdWords User.</param>
/// <returns>The feed details.</returns>
private static DSAFeedDetails CreateFeed(AdWordsUser user)
{
using (FeedService feedService =
(FeedService) user.GetService(AdWordsService.v201809.FeedService))
{
// Create attributes.
FeedAttribute urlAttribute = new FeedAttribute
{
type = FeedAttributeType.URL_LIST,
name = "Page URL"
};
FeedAttribute labelAttribute = new FeedAttribute
{
type = FeedAttributeType.STRING_LIST,
name = "Label"
};
// Create the feed.
Feed sitelinksFeed = new Feed
{
name = "DSA Feed " + ExampleUtilities.GetRandomString(),
attributes = new FeedAttribute[]
{
urlAttribute,
labelAttribute
},
origin = FeedOrigin.USER
};
// Create operation.
FeedOperation operation = new FeedOperation
{
operand = sitelinksFeed,
@operator = Operator.ADD
};
try
{
// Add the feed.
FeedReturnValue result = feedService.mutate(new FeedOperation[]
{
operation
});
Feed savedFeed = result.value[0];
return new DSAFeedDetails
{
feedId = savedFeed.id,
urlAttributeId = savedFeed.attributes[0].id,
labelAttributeId = savedFeed.attributes[1].id,
};
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to create DSA feed.", e);
}
}
}
/// <summary>
/// Creates the feed mapping for DSA page feeds.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="feedDetails">The feed details.</param>
private static void CreateFeedMapping(AdWordsUser user, DSAFeedDetails feedDetails)
{
using (FeedMappingService feedMappingService =
(FeedMappingService) user.GetService(AdWordsService.v201809.FeedMappingService))
{
// Map the FeedAttributeIds to the fieldId constants.
AttributeFieldMapping urlFieldMapping = new AttributeFieldMapping
{
feedAttributeId = feedDetails.urlAttributeId,
fieldId = DSA_PAGE_URLS_FIELD_ID
};
AttributeFieldMapping labelFieldMapping = new AttributeFieldMapping
{
feedAttributeId = feedDetails.labelAttributeId,
fieldId = DSA_LABEL_FIELD_ID
};
// Create the FieldMapping and operation.
FeedMapping feedMapping = new FeedMapping
{
criterionType = DSA_PAGE_FEED_CRITERION_TYPE,
feedId = feedDetails.feedId,
attributeFieldMappings = new AttributeFieldMapping[]
{
urlFieldMapping,
labelFieldMapping
}
};
FeedMappingOperation operation = new FeedMappingOperation
{
operand = feedMapping,
@operator = Operator.ADD
};
try
{
// Add the field mapping.
feedMappingService.mutate(new FeedMappingOperation[]
{
operation
});
return;
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to create feed mapping.", e);
}
}
}
/// <summary>
/// Creates the page URLs in the DSA page feed.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="feedDetails">The feed details.</param>
/// <param name="labelName">The pagefeed url label.</param>
private static void CreateFeedItems(AdWordsUser user, DSAFeedDetails feedDetails,
string labelName)
{
using (FeedItemService feedItemService =
(FeedItemService) user.GetService(AdWordsService.v201809.FeedItemService))
{
FeedItemOperation[] operations = new FeedItemOperation[]
{
CreateDsaUrlAddOperation(feedDetails,
"http://www.example.com/discounts/rental-cars", labelName),
CreateDsaUrlAddOperation(feedDetails,
"http://www.example.com/discounts/hotel-deals", labelName),
CreateDsaUrlAddOperation(feedDetails,
"http://www.example.com/discounts/flight-deals", labelName),
};
feedItemService.mutate(operations);
}
}
/// <summary>
/// Creates the DSA URL add operation.
/// </summary>
/// <param name="details">The page feed details.</param>
/// <param name="url">The DSA page feed URL.</param>
/// <param name="label">DSA page feed label.</param>
/// <returns>The DSA URL add operation.</returns>
private static FeedItemOperation CreateDsaUrlAddOperation(DSAFeedDetails details,
string url, string label)
{
// Create the FeedItemAttributeValues for our text values.
FeedItemAttributeValue urlAttributeValue = new FeedItemAttributeValue
{
feedAttributeId = details.urlAttributeId,
// See https://support.google.com/adwords/answer/7166527 for page feed URL
// recommendations and rules.
stringValues = new string[]
{
url
}
};
FeedItemAttributeValue labelAttributeValue = new FeedItemAttributeValue
{
feedAttributeId = details.labelAttributeId,
stringValues = new string[]
{
label
}
};
// Create the feed item and operation.
FeedItem item = new FeedItem
{
feedId = details.feedId,
attributeValues = new FeedItemAttributeValue[]
{
urlAttributeValue,
labelAttributeValue
}
};
FeedItemOperation operation = new FeedItemOperation
{
operand = item,
@operator = Operator.ADD
};
return operation;
}
/// <summary>
/// Updates the campaign DSA setting to add DSA pagefeeds.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">The Campaign ID.</param>
/// <param name="feedId">The page feed ID.</param>
private static void UpdateCampaignDsaSetting(AdWordsUser user, long campaignId, long feedId)
{
using (CampaignService campaignService =
(CampaignService) user.GetService(AdWordsService.v201809.CampaignService))
{
Selector selector = new Selector()
{
fields = new string[]
{
Campaign.Fields.Id,
Campaign.Fields.Settings
},
predicates = new Predicate[]
{
Predicate.Equals(Campaign.Fields.Id, campaignId)
},
paging = Paging.Default
};
CampaignPage page = campaignService.get(selector);
if (page == null || page.entries == null || page.entries.Length == 0)
{
throw new System.ApplicationException(
string.Format("Failed to retrieve campaign with ID = {0}.", campaignId));
}
Campaign campaign = page.entries[0];
if (campaign.settings == null)
{
throw new System.ApplicationException("This is not a DSA campaign.");
}
DynamicSearchAdsSetting dsaSetting = null;
Setting[] campaignSettings = campaign.settings;
for (int i = 0; i < campaign.settings.Length; i++)
{
Setting setting = campaignSettings[i];
if (setting is DynamicSearchAdsSetting)
{
dsaSetting = (DynamicSearchAdsSetting) setting;
break;
}
}
if (dsaSetting == null)
{
throw new System.ApplicationException("This is not a DSA campaign.");
}
// Use a page feed to specify precisely which URLs to use with your
// Dynamic Search Ads.
dsaSetting.pageFeed = new PageFeed()
{
feedIds = new long[]
{
feedId
},
};
// Optional: Specify whether only the supplied URLs should be used with your
// Dynamic Search Ads.
dsaSetting.useSuppliedUrlsOnly = true;
Campaign campaignToUpdate = new Campaign
{
id = campaignId,
settings = campaignSettings
};
CampaignOperation operation = new CampaignOperation
{
operand = campaignToUpdate,
@operator = Operator.SET
};
try
{
CampaignReturnValue retval = campaignService.mutate(new CampaignOperation[]
{
operation
});
Campaign updatedCampaign = retval.value[0];
Console.WriteLine(
"DSA page feed for campaign ID '{0}' was updated with feed ID '{1}'.",
updatedCampaign.id, feedId);
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to set page feed for campaign.",
e);
}
}
}
/// <summary>
/// Set custom targeting for the page feed URLs based on a list of labels.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="adGroupId">Ad group ID.</param>
/// <param name="labelName">The label name.</param>
/// <returns>The newly created webpage criterion.</returns>
private static BiddableAdGroupCriterion AddDsaTargeting(AdWordsUser user, long adGroupId,
string labelName)
{
using (AdGroupCriterionService adGroupCriterionService =
(AdGroupCriterionService) user.GetService(AdWordsService.v201809
.AdGroupCriterionService))
{
// Create a webpage criterion.
Webpage webpage = new Webpage();
WebpageParameter parameter = new WebpageParameter
{
criterionName = "Test criterion"
};
webpage.parameter = parameter;
// Add a condition for label=specified_label_name.
WebpageCondition condition = new WebpageCondition
{
operand = WebpageConditionOperand.CUSTOM_LABEL,
argument = labelName
};
parameter.conditions = new WebpageCondition[]
{
condition
};
BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion
{
adGroupId = adGroupId,
criterion = webpage
};
// Set a custom bid for this criterion.
BiddingStrategyConfiguration biddingStrategyConfiguration =
new BiddingStrategyConfiguration
{
bids = new Bids[]
{
new CpcBid()
{
bid = new Money()
{
microAmount = 1500000
}
}
}
};
criterion.biddingStrategyConfiguration = biddingStrategyConfiguration;
AdGroupCriterionOperation operation = new AdGroupCriterionOperation
{
operand = criterion,
@operator = Operator.ADD
};
try
{
AdGroupCriterionReturnValue retval = adGroupCriterionService.mutate(
new AdGroupCriterionOperation[]
{
operation
});
BiddableAdGroupCriterion newCriterion =
(BiddableAdGroupCriterion) retval.value[0];
Console.WriteLine(
"Web page criterion with ID = {0} and status = {1} was created.",
newCriterion.criterion.id, newCriterion.userStatus);
return newCriterion;
}
catch (Exception e)
{
throw new System.ApplicationException(
"Failed to create webpage criterion for " + "custom page feed label.", e);
}
}
}
}
}