public void Run(Object obj)
{
// Create the operations.
List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>();
for (int j = 0; j < NUM_KEYWORDS; j++) {
// Create the keyword.
Keyword keyword = new Keyword();
keyword.text = "mars cruise thread " + threadIndex.ToString() + " seed " + j.ToString();
keyword.matchType = KeywordMatchType.BROAD;
// Create the biddable ad group criterion.
AdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion();
keywordCriterion.adGroupId = adGroupId;
keywordCriterion.criterion = keyword;
// Create the operations.
AdGroupCriterionOperation keywordOperation = new AdGroupCriterionOperation();
keywordOperation.@operator = Operator.ADD;
keywordOperation.operand = keywordCriterion;
operations.Add(keywordOperation);
}
// Get the AdGroupCriterionService. This should be done within the
// thread, since a service can only handle one outgoing HTTP request
// at a time.
AdGroupCriterionService service = (AdGroupCriterionService) user.GetService(
AdWordsService.v201306.AdGroupCriterionService);
service.RequestHeader.validateOnly = true;
int retryCount = 0;
const int NUM_RETRIES = 3;
try {
while (retryCount < NUM_RETRIES) {
try {
// Validate the keywords.
AdGroupCriterionReturnValue retval = service.mutate(operations.ToArray());
break;
} catch (AdWordsApiException ex) {
// Handle API errors.
ApiException innerException = ex.ApiException as ApiException;
if (innerException == null) {
throw new Exception("Failed to retrieve ApiError. See inner exception for more " +
"details.", ex);
}
foreach (ApiError apiError in innerException.errors) {
if (!(apiError is RateExceededError)) {
// Rethrow any errors other than RateExceededError.
throw;
}
// Handle rate exceeded errors.
RateExceededError rateExceededError = (RateExceededError) apiError;
Console.WriteLine("Got Rate exceeded error - rate name = '{0}', scope = '{1}', " +
"retry After {2} seconds.", rateExceededError.rateScope,
rateExceededError.rateName, rateExceededError.retryAfterSeconds);
Thread.Sleep(rateExceededError.retryAfterSeconds * 1000);
retryCount = retryCount + 1;
}
} finally {
if (retryCount == NUM_RETRIES) {
throw new Exception(String.Format("Could not recover after making {0} attempts.",
retryCount));
}
}
}
} catch (Exception ex) {
throw new System.ApplicationException("Failed to validate keywords.", ex);
}
}