/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">Id of the campaign to which keywords are added.</param>
public void Run(AdWordsUser user, long campaignId) {
try {
// Create a shared set.
SharedSet sharedSet = CreateSharedKeywordSet(user);
Console.WriteLine("Shared set with id = {0}, name = {1}, type = {2}, status = {3} " +
"was created.", sharedSet.sharedSetId, sharedSet.name, sharedSet.type,
sharedSet.status);
// Add new keywords to the shared set.
string[] keywordTexts = new string[] {"mars cruise", "mars hotels"};
SharedCriterion[] sharedCriteria = AddKeywordsToSharedSet(user, sharedSet.sharedSetId,
keywordTexts);
foreach (SharedCriterion sharedCriterion in sharedCriteria) {
Keyword keyword = sharedCriterion.criterion as Keyword;
Console.WriteLine("Added keyword with id = {0}, text = {1}, matchtype = {2} to " +
"shared set with id = {3}.", keyword.id, keyword.text, keyword.matchType,
sharedSet.sharedSetId);
}
// Attach the shared set to the campaign.
CampaignSharedSet attachedSharedSet = AttachSharedSetToCampaign(user, campaignId,
sharedSet.sharedSetId);
Console.WriteLine("Attached shared set with id = {0} to campaign id {1}.",
attachedSharedSet.sharedSetId, attachedSharedSet.campaignId);
} catch (Exception ex) {
throw new System.ApplicationException("Failed to create shared keyword set and attach " +
"it to a campaign.", ex);
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="fileName">The file to which the report is downloaded.
/// </param>
public void Run(AdWordsUser user, string fileName)
{
string query = "SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, Impressions, " +
"Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT WHERE Status IN [ACTIVE, PAUSED] " +
"DURING LAST_7_DAYS";
string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName;
try {
// If you know that your report is small enough to fit in memory, then
// you can instead use
// ReportUtilities utilities = new ReportUtilities(user);
// utilities.ReportVersion = "v201306";
// ClientReport report = utilities.GetClientReport(query, format);
//
// // Get the text report directly if you requested a text format
// // (e.g. xml)
// string reportText = report.Text;
//
// // Get the binary report if you requested a binary format
// // (e.g. gzip)
// byte[] reportBytes = report.Contents;
//
// // Deflate a zipped binary report for further processing.
// string deflatedReportText = Encoding.UTF8.GetString(
// MediaUtilities.DeflateGZipData(report.Contents));
ReportUtilities utilities = new ReportUtilities(user);
utilities.ReportVersion = "v201306";
utilities.DownloadClientReport(query, DownloadFormat.GZIPPED_CSV.ToString(), filePath);
Console.WriteLine("Report was downloaded to '{0}'.", filePath);
} catch (Exception ex) {
throw new System.ApplicationException("Failed to download report.", ex);
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="adGroupId">ID of the ad group that contains the ad.</param>
/// <param name="adId">ID of the ad to be upgraded.</param>
public void Run(AdWordsUser user, long adGroupId, long adId) {
// Get the AdGroupAdService.
AdGroupAdService adGroupAdService = (AdGroupAdService)
user.GetService(AdWordsService.v201502.AdGroupAdService);
try {
// Retrieve the Ad.
AdGroupAd adGroupAd = GetAdGroupAd(adGroupAdService, adGroupId, adId);
if (adGroupAd == null) {
Console.WriteLine("Ad not found.");
return;
}
// Copy the destination url to the final url.
AdUrlUpgrade upgradeUrl = new AdUrlUpgrade();
upgradeUrl.adId = adGroupAd.ad.id;
upgradeUrl.finalUrl = adGroupAd.ad.url;
// Upgrade the ad.
Ad[] upgradedAds = adGroupAdService.upgradeUrl(new AdUrlUpgrade[] { upgradeUrl });
// Display the results.
if (upgradedAds != null && upgradedAds.Length > 0) {
foreach (Ad upgradedAd in upgradedAds) {
Console.WriteLine("Ad with id = {0} and destination url = {1} was upgraded.",
upgradedAd.id, upgradedAd.finalUrls[0]);
}
} else {
Console.WriteLine("No ads were upgraded.");
}
} catch (Exception ex) {
throw new System.ApplicationException("Failed to upgrade ads.", ex);
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
public void Run(AdWordsUser user)
{
// Get the MediaService.
MediaService mediaService = (MediaService) user.GetService(
AdWordsService.v201502.MediaService);
// Create a selector.
Selector selector = new Selector();
selector.fields = new string[] {"MediaId", "Width", "Height", "MimeType"};
// Set the filter.
Predicate predicate = new Predicate();
[email protected] = PredicateOperator.IN;
predicate.field = "Type";
predicate.values = new string[] {MediaMediaType.VIDEO.ToString(),
MediaMediaType.IMAGE.ToString()};
selector.predicates = new Predicate[] {predicate};
// Set selector paging.
selector.paging = new Paging();
int offset = 0;
int pageSize = 500;
MediaPage page = new MediaPage();
try {
do {
selector.paging.startIndex = offset;
selector.paging.numberResults = pageSize;
page = mediaService.get(selector);
if (page != null && page.entries != null) {
int i = offset;
foreach (Media media in page.entries) {
if (media is Video) {
Video video = (Video) media;
Console.WriteLine("{0}) Video with id \"{1}\" and name \"{2}\" was found.",
i, video.mediaId, video.name);
} else if (media is Image) {
Image image = (Image) media;
Dictionary<MediaSize, Dimensions> dimensions =
CreateMediaDimensionMap(image.dimensions);
Console.WriteLine("{0}) Image with id '{1}', dimensions '{2}x{3}', and MIME type " +
"'{4}' was found.", i, image.mediaId, dimensions[MediaSize.FULL].width,
dimensions[MediaSize.FULL].height, image.mimeType);
}
i++;
}
}
offset += pageSize;
} while (offset < page.totalNumEntries);
Console.WriteLine("Number of images and videos found: {0}", page.totalNumEntries);
} catch (Exception e) {
throw new System.ApplicationException("Failed to get images and videos.", e);
}
}
/// <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) {
AddGoogleMyBusinessLocationExtensions codeExample =
new AddGoogleMyBusinessLocationExtensions();
Console.WriteLine(codeExample.Description);
AdWordsUser user = new AdWordsUser();
try {
// The email address of either an owner or a manager of the GMB account.
string gmbEmailAddress = "INSERT_GMB_EMAIL_ADDRESS_HERE";
// Refresh the access token so that there's a valid access token.
user.OAuthProvider.RefreshAccessToken();
// If the gmbEmailAddress above is the same user you used to generate
// your AdWords API refresh token, leave the assignment below unchanged.
// Otherwise, to obtain an access token for your GMB account, run the
// OAuth Token generator utility while logged in as the same user as
// gmbEmailAddress. Copy and paste the AccessToken value into the
// assignment below.
string gmbAccessToken = user.OAuthProvider.AccessToken;
// If the gmbEmailAddress above is for a GMB manager instead of the GMB
// account owner, then set businessAccountIdentifier to the +Page ID of
// a location for which the manager has access. See the location
// extensions guide at
// https://developers.google.com/adwords/api/docs/guides/feed-services-locations
// for details.
String businessAccountIdentifier = null;
codeExample.Run(user, gmbEmailAddress, gmbAccessToken, businessAccountIdentifier);
} catch (Exception e) {
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Creates a new Feed for ad customizers.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="feedName">Name of the feed to be created.</param>
/// <returns>A new Ad customizer feed.</returns>
private static AdCustomizerFeed CreateCustomizerFeed(AdWordsUser user, string feedName) {
AdCustomizerFeedService adCustomizerFeedService = (AdCustomizerFeedService) user.GetService(
AdWordsService.v201509.AdCustomizerFeedService);
AdCustomizerFeed feed = new AdCustomizerFeed() {
feedName = feedName,
feedAttributes = new AdCustomizerFeedAttribute[] {
new AdCustomizerFeedAttribute() {
name = "Name",
type = AdCustomizerFeedAttributeType.STRING
},
new AdCustomizerFeedAttribute() {
name = "Price",
type = AdCustomizerFeedAttributeType.PRICE
},
new AdCustomizerFeedAttribute() {
name = "Date",
type = AdCustomizerFeedAttributeType.DATE_TIME
},
}
};
AdCustomizerFeedOperation feedOperation = new AdCustomizerFeedOperation();
feedOperation.operand = feed;
[email protected] = (Operator.ADD);
AdCustomizerFeed addedFeed = adCustomizerFeedService.mutate(
new AdCustomizerFeedOperation[] { feedOperation }).value[0];
Console.WriteLine("Created ad customizer feed with ID = {0} and name = '{1}'.",
addedFeed.feedId, addedFeed.feedName);
return addedFeed;
}
/// <summary>
/// Gets the quota usage of an account in units, broken down by
/// method name.
/// </summary>
/// <param name="user">The AdWordsUser object for which the quota usage
/// should be retrieved.</param>
/// <param name="startDate">Start date for the date range for which
/// results are to be retrieved.</param>
/// <param name="endDate">End date for the date range for which results
/// are to be retrieved.</param>
/// <returns>A list of MethodQuotaUsage objects, with one entry for each
/// method.</returns>
public static List<MethodQuotaUsage> GetMethodQuotaUsage(AdWordsUser user, DateTime startDate,
DateTime endDate) {
List<MethodQuotaUsage> methodQuotaUsageList = new List<MethodQuotaUsage>();
SortedList<string, List<string>> serviceToMethodsMap = GetAllMethods();
InfoService service = (InfoService) user.GetService(AdWordsService.v201109.InfoService);
foreach (string serviceName in serviceToMethodsMap.Keys) {
List<string> methods = serviceToMethodsMap[serviceName];
foreach (string methodName in methods) {
InfoSelector selector = new InfoSelector();
selector.apiUsageTypeSpecified = true;
selector.apiUsageType = ApiUsageType.UNIT_COUNT;
selector.dateRange = new DateRange();
selector.dateRange.min = startDate.ToString("YYYYMMDD");
selector.dateRange.max = endDate.ToString("YYYYMMDD");
selector.serviceName = serviceName;
if (methodName.Contains(".")) {
string[] splits = methodName.Split('.');
selector.methodName = splits[0];
selector.operatorSpecified = true;
[email protected] = (Operator) Enum.Parse(typeof(Operator), splits[1]);
} else {
selector.methodName = methodName;
}
methodQuotaUsageList.Add(new MethodQuotaUsage(serviceName, methodName,
service.get(selector).cost));
}
}
return methodQuotaUsageList;
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
public void Run(AdWordsUser user)
{
// Use a test account for which 2 factor authentication has been enabled.
string loginEmail = "[email protected]";
string password = "testaccount";
AdWordsAppConfig config = new AdWordsAppConfig();
config.Email = loginEmail;
config.Password = password;
AuthToken authToken = new AuthToken(config, "adwords");
try {
// Try to obtain an authToken.
string token = authToken.GetToken();
Console.WriteLine("Retrieved an authToken = {0} for user {1}.", token, loginEmail);
} catch (AuthTokenException ex) {
// Since the test account has 2 factor authentication enabled, this block
// of code will be executed.
if (ex.ErrorCode == AuthTokenErrorCode.BadAuthentication) {
if (ex.Info == "InvalidSecondFactor") {
Console.WriteLine("The user has enabled two factor authentication in this " +
"account. Have the user generate an application-specific password to make " +
"calls against the AdWords API. See " +
"http://adwordsapi.blogspot.com/2011/02/authentication-changes-with-2-step.html" +
" for more details.");
} else {
Console.WriteLine("Invalid credentials.");
}
} else {
throw new System.ApplicationException(String.Format("The server raised an {0} error.",
ex.ErrorCode));
}
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="adGroupId">Id of the ad group to be removed.</param>
public void Run(AdWordsUser user, long adGroupId) {
// Get the AdGroupService.
AdGroupService adGroupService = (AdGroupService) user.GetService(
AdWordsService.v201506.AdGroupService);
// Create ad group with REMOVED status.
AdGroup adGroup = new AdGroup();
adGroup.id = adGroupId;
adGroup.status = AdGroupStatus.REMOVED;
// Create the operation.
AdGroupOperation operation = new AdGroupOperation();
operation.operand = adGroup;
[email protected] = Operator.SET;
try {
// Remove the ad group.
AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] {operation});
// Display the results.
if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
AdGroup removedAdGroup = retVal.value[0];
Console.WriteLine("Ad group with id = \"{0}\" and name = \"{1}\" was removed.",
removedAdGroup.id, removedAdGroup.name);
} else {
Console.WriteLine("No ad groups were removed.");
}
} catch (Exception e) {
throw new System.ApplicationException("Failed to remove ad group.", e);
}
}
请发表评论