-
Notifications
You must be signed in to change notification settings - Fork 199
/
AddCompleteCampaignsUsingBatchJob.cs
executable file
·420 lines (370 loc) · 16.4 KB
/
AddCompleteCampaignsUsingBatchJob.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
// 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.Util.BatchJob.v201809;
using Google.Api.Ads.AdWords.v201809;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code sample illustrates how to use BatchJobService to create multiple
/// complete campaigns, including ad groups and keywords.
/// </summary>
public class AddCompleteCampaignsUsingBatchJob : ExampleBase
{
/// <summary>
/// The last ID that was automatically generated.
/// </summary>
private static long LAST_ID = -1;
/// <summary>
/// The number of campaigns to be added.
/// </summary>
private const long NUMBER_OF_CAMPAIGNS_TO_ADD = 2;
/// <summary>
/// The number of ad groups to be added per campaign.
/// </summary>
private const long NUMBER_OF_ADGROUPS_TO_ADD = 2;
/// <summary>
/// The number of keywords to be added per campaign.
/// </summary>
private const long NUMBER_OF_KEYWORDS_TO_ADD = 5;
/// <summary>
/// The polling interval base to be used for exponential backoff.
/// </summary>
private const int POLL_INTERVAL_SECONDS_BASE = 30;
/// <summary>
/// The maximum milliseconds to wait for completion.
/// </summary>
private const int TIME_TO_WAIT_FOR_COMPLETION = 15 * 60 * 1000; // 15 minutes
/// <summary>
/// Create a temporary ID generator that will produce a sequence of descending
/// negative numbers.
/// </summary>
/// <returns></returns>
private static long NextId()
{
return Interlocked.Decrement(ref LAST_ID);
}
/// <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)
{
AddCompleteCampaignsUsingBatchJob codeExample = new AddCompleteCampaignsUsingBatchJob();
Console.WriteLine(codeExample.Description);
try
{
codeExample.Run(new AdWordsUser());
}
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 sample illustrates how to use BatchJobService to create multiple " +
"complete campaigns, including ad groups and keywords.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
public void Run(AdWordsUser user)
{
using (BatchJobService batchJobService =
(BatchJobService) user.GetService(AdWordsService.v201809.BatchJobService))
{
try
{
// Create a BatchJob.
BatchJobOperation addOp = new BatchJobOperation()
{
@operator = Operator.ADD,
operand = new BatchJob()
};
BatchJob batchJob = batchJobService.mutate(new BatchJobOperation[]
{
addOp
}).value[0];
// Get the upload URL from the new job.
string uploadUrl = batchJob.uploadUrl.url;
Console.WriteLine(
"Created BatchJob with ID {0}, status '{1}' and upload URL {2}.",
batchJob.id, batchJob.status, batchJob.uploadUrl.url);
// Create the mutate request that will be sent to the upload URL.
List<Operation> operations = new List<Operation>();
// Create and add an operation to create a new budget.
BudgetOperation budgetOperation = BuildBudgetOperation();
operations.Add(budgetOperation);
// Create and add operations to create new campaigns.
List<CampaignOperation> campaignOperations =
BuildCampaignOperations(budgetOperation.operand.budgetId);
operations.AddRange(campaignOperations);
// Create and add operations to create new ad groups.
List<AdGroupOperation> adGroupOperations = new List<AdGroupOperation>();
foreach (CampaignOperation campaignOperation in campaignOperations)
{
adGroupOperations.AddRange(
BuildAdGroupOperations(campaignOperation.operand.id));
}
operations.AddRange(adGroupOperations);
// Create and add operations to create new ad group ads (expanded text ads).
foreach (AdGroupOperation adGroupOperation in adGroupOperations)
{
operations.AddRange(BuildAdGroupAdOperations(adGroupOperation.operand.id));
}
// Create and add operations to create new ad group criteria (keywords).
foreach (AdGroupOperation adGroupOperation in adGroupOperations)
{
operations.AddRange(
BuildAdGroupCriterionOperations(adGroupOperation.operand.id));
}
BatchJobUtilities batchJobUploadHelper = new BatchJobUtilities(user);
// Create a resumable Upload URL to upload the operations.
string resumableUploadUrl =
batchJobUploadHelper.GetResumableUploadUrl(uploadUrl);
// Use the BatchJobUploadHelper to upload all operations.
batchJobUploadHelper.Upload(resumableUploadUrl, operations);
bool isCompleted = batchJobUploadHelper.WaitForPendingJob(batchJob.id,
TIME_TO_WAIT_FOR_COMPLETION,
delegate(BatchJob waitBatchJob, long timeElapsed)
{
Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
timeElapsed / 1000, waitBatchJob.id, waitBatchJob.status);
batchJob = waitBatchJob;
return false;
});
if (!isCompleted)
{
throw new TimeoutException(
"Job is still in pending state after waiting for " +
TIME_TO_WAIT_FOR_COMPLETION + " seconds.");
}
if (batchJob.processingErrors != null)
{
foreach (BatchJobProcessingError processingError in batchJob
.processingErrors)
{
Console.WriteLine(" Processing error: {0}, {1}, {2}, {3}, {4}",
processingError.ApiErrorType, processingError.trigger,
processingError.errorString, processingError.fieldPath,
processingError.reason);
}
}
if (batchJob.downloadUrl != null && batchJob.downloadUrl.url != null)
{
BatchJobMutateResponse mutateResponse =
batchJobUploadHelper.Download(batchJob.downloadUrl.url);
Console.WriteLine("Downloaded results from {0}.", batchJob.downloadUrl.url);
foreach (MutateResult mutateResult in mutateResponse.rval)
{
string outcome = mutateResult.errorList == null ? "SUCCESS" : "FAILURE";
Console.WriteLine(" Operation [{0}] - {1}", mutateResult.index,
outcome);
}
}
}
catch (Exception e)
{
throw new System.ApplicationException(
"Failed to add campaigns using batch job.", e);
}
}
}
/// <summary>
/// Builds the operation for creating an ad within an ad group.
/// </summary>
/// <param name="adGroupId">ID of the ad group for which ads are created.</param>
/// <returns>A list of operations for creating ads.</returns>
private static List<AdGroupAdOperation> BuildAdGroupAdOperations(long adGroupId)
{
List<AdGroupAdOperation> operations = new List<AdGroupAdOperation>();
AdGroupAd adGroupAd = new AdGroupAd()
{
adGroupId = adGroupId,
ad = new ExpandedTextAd()
{
headlinePart1 = "Luxury Cruise to Mars",
headlinePart2 = "Visit the Red Planet in style.",
description = "Low-gravity fun for everyone!",
finalUrls = new string[]
{
"http://www.example.com/1"
}
}
};
AdGroupAdOperation operation = new AdGroupAdOperation()
{
operand = adGroupAd,
@operator = Operator.ADD
};
operations.Add(operation);
return operations;
}
/// <summary>
/// Builds the operations for creating keywords within an ad group.
/// </summary>
/// <param name="adGroupId">ID of the ad group for which keywords are
/// created.</param>
/// <returns>A list of operations for creating keywords.</returns>
private static List<AdGroupCriterionOperation> BuildAdGroupCriterionOperations(
long adGroupId)
{
List<AdGroupCriterionOperation> adGroupCriteriaOperations =
new List<AdGroupCriterionOperation>();
// Create AdGroupCriterionOperations to add keywords.
for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++)
{
// Create Keyword.
string text = string.Format("mars{0}", i);
// Make 50% of keywords invalid to demonstrate error handling.
if ((i % 2) == 0)
{
text = text + "!!!";
}
// Create AdGroupCriterionOperation.
AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
{
operand = new BiddableAdGroupCriterion()
{
adGroupId = adGroupId,
criterion = new Keyword()
{
text = text,
matchType = KeywordMatchType.BROAD
}
},
@operator = Operator.ADD
};
// Add to list.
adGroupCriteriaOperations.Add(operation);
}
return adGroupCriteriaOperations;
}
/// <summary>
/// Builds the operations for creating ad groups within a campaign.
/// </summary>
/// <param name="campaignId">ID of the campaign for which ad groups are
/// created.</param>
/// <returns>A list of operations for creating ad groups.</returns>
private static List<AdGroupOperation> BuildAdGroupOperations(long campaignId)
{
List<AdGroupOperation> operations = new List<AdGroupOperation>();
for (int i = 0; i < NUMBER_OF_ADGROUPS_TO_ADD; i++)
{
AdGroup adGroup = new AdGroup()
{
campaignId = campaignId,
id = NextId(),
name = "Batch Ad Group # " + ExampleUtilities.GetRandomString(),
biddingStrategyConfiguration = new BiddingStrategyConfiguration()
{
bids = new Bids[]
{
new CpcBid()
{
bid = new Money()
{
microAmount = 10000000L
}
}
}
}
};
AdGroupOperation operation = new AdGroupOperation()
{
operand = adGroup,
@operator = Operator.ADD
};
operations.Add(operation);
}
return operations;
}
/// <summary>
/// Builds the operations for creating new campaigns.
/// </summary>
/// <param name="budgetId">ID of the budget to be used for the campaign.
/// </param>
/// <returns>A list of operations for creating campaigns.</returns>
private static List<CampaignOperation> BuildCampaignOperations(long budgetId)
{
List<CampaignOperation> operations = new List<CampaignOperation>();
for (int i = 0; i < NUMBER_OF_CAMPAIGNS_TO_ADD; i++)
{
Campaign campaign = new Campaign()
{
name = "Batch Campaign " + ExampleUtilities.GetRandomString(),
// Recommendation: Set the campaign to PAUSED when creating it to prevent
// the ads from immediately serving. Set to ENABLED once you've added
// targeting and the ads are ready to serve.
status = CampaignStatus.PAUSED,
id = NextId(),
advertisingChannelType = AdvertisingChannelType.SEARCH,
budget = new Budget()
{
budgetId = budgetId
},
biddingStrategyConfiguration = new BiddingStrategyConfiguration()
{
biddingStrategyType = BiddingStrategyType.MANUAL_CPC,
// You can optionally provide a bidding scheme in place of the type.
biddingScheme = new ManualCpcBiddingScheme()
}
};
CampaignOperation operation = new CampaignOperation()
{
operand = campaign,
@operator = Operator.ADD
};
operations.Add(operation);
}
return operations;
}
/// <summary>
/// Builds an operation for creating a budget.
/// </summary>
/// <returns>The operation for creating a budget.</returns>
private static BudgetOperation BuildBudgetOperation()
{
Budget budget = new Budget()
{
budgetId = NextId(),
name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
amount = new Money()
{
microAmount = 50000000L,
},
deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
};
BudgetOperation budgetOperation = new BudgetOperation()
{
operand = budget,
@operator = Operator.ADD
};
return budgetOperation;
}
}
}