/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="queryString">The video search query text.</param> public void Run(AdWordsUser user, string queryString) { // Get the VideoService. VideoService videoService = (VideoService) user.GetService( AdWordsService.v201406.VideoService); // Create a selector. VideoSearchSelector selector = new VideoSearchSelector(); selector.searchType = VideoSearchSelectorSearchType.VIDEO; selector.query = queryString; selector.paging = new Paging(); selector.paging.startIndex = 0; selector.paging.numberResults = PAGE_SIZE; try { // Run the query. VideoSearchPage page = videoService.search(selector); // Display videos. if (page != null && page.totalNumEntries > 0) { foreach (YouTubeVideo video in page.entries) { Console.WriteLine("YouTube video ID {0} with title {1} found.", video.id, video.title); } Console.WriteLine("Total number of matching videos: {0}.", page.totalNumEntries); } else { Console.WriteLine("No videos matching {0} were found.", queryString); } } catch (Exception ex) { throw new System.ApplicationException("Failed to search for videos.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="reportType">The report type to be run.</param> public void Run(AdWordsUser user, ReportDefinitionReportType reportType) { // Get the ReportDefinitionService. ReportDefinitionService reportDefinitionService = (ReportDefinitionService) user.GetService( AdWordsService.v201509.ReportDefinitionService); try { // Get the report fields. ReportDefinitionField[] reportDefinitionFields = reportDefinitionService.getReportFields( reportType); if (reportDefinitionFields != null && reportDefinitionFields.Length > 0) { // Display report fields. Console.WriteLine("The report type '{0}' contains the following fields:", reportType); foreach (ReportDefinitionField reportDefinitionField in reportDefinitionFields) { Console.Write("- {0} ({1})", reportDefinitionField.fieldName, reportDefinitionField.fieldType); if (reportDefinitionField.enumValues != null) { Console.Write(" := [{0}]", String.Join(", ", reportDefinitionField.enumValues)); } Console.WriteLine(); } } else { Console.WriteLine("This report type has no fields."); } } catch (Exception e) { throw new System.ApplicationException("Failed to retrieve fields for report type.", e); } }
/// <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> public void Run(AdWordsUser user) { // Get the ManagedCustomerService. ManagedCustomerService managedCustomerService = (ManagedCustomerService) user.GetService( AdWordsService.v201306.ManagedCustomerService); managedCustomerService.RequestHeader.clientCustomerId = null; // Create selector. Selector selector = new Selector(); selector.fields = new String[] {"Login", "CustomerId", "Name"}; try { // Get results. ManagedCustomerPage page = managedCustomerService.get(selector); // Display serviced account graph. if (page.entries != null) { // Create map from customerId to customer node. Dictionary<long, ManagedCustomerTreeNode> customerIdToCustomerNode = new Dictionary<long, ManagedCustomerTreeNode>(); // Create account tree nodes for each customer. foreach (ManagedCustomer customer in page.entries) { ManagedCustomerTreeNode node = new ManagedCustomerTreeNode(); node.Account = customer; customerIdToCustomerNode.Add(customer.customerId, node); } // For each link, connect nodes in tree. if (page.links != null) { foreach (ManagedCustomerLink link in page.links) { ManagedCustomerTreeNode managerNode = customerIdToCustomerNode[link.managerCustomerId]; ManagedCustomerTreeNode childNode = customerIdToCustomerNode[link.clientCustomerId]; childNode.ParentNode = managerNode; if (managerNode != null) { managerNode.ChildAccounts.Add(childNode); } } } // Find the root account node in the tree. ManagedCustomerTreeNode rootNode = null; foreach (ManagedCustomer account in page.entries) { if (customerIdToCustomerNode[account.customerId].ParentNode == null) { rootNode = customerIdToCustomerNode[account.customerId]; break; } } // Display account tree. Console.WriteLine("Login, CustomerId, Name"); Console.WriteLine(rootNode.ToTreeString(0, new StringBuilder())); } else { Console.WriteLine("No serviced accounts were found."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create ad groups.", 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> /// <param name="fileName">The file to which the report is downloaded. /// </param> public void Run(AdWordsUser user, string fileName) { ReportDefinition definition = new ReportDefinition() { reportName = "Last 7 days CRITERIA_PERFORMANCE_REPORT", reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT, downloadFormat = DownloadFormat.GZIPPED_CSV, dateRangeType = ReportDefinitionDateRangeType.LAST_7_DAYS, selector = new Selector() { fields = new string[] {"CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria", "FinalUrls", "Clicks", "Impressions", "Cost"}, predicates = new Predicate[] { Predicate.In("Status", new string[] {"ENABLED", "PAUSED"}) } }, // Optional: Include zero impression rows. includeZeroImpressions = true }; string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName; try { ReportUtilities utilities = new ReportUtilities(user, "v201502", definition); using (ReportResponse response = utilities.GetResponse()) { response.Save(filePath); } Console.WriteLine("Report was downloaded to '{0}'.", filePath); } catch (Exception e) { throw new System.ApplicationException("Failed to download report.", e); } }
/// <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(); predicate.@operator = 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> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to be deleted.</param> public void Run(AdWordsUser user, long campaignId) { // Get the CampaignService. CampaignService campaignService = (CampaignService) user.GetService( AdWordsService.v201402.CampaignService); // Create campaign with DELETED status. Campaign campaign = new Campaign(); campaign.id = campaignId; campaign.status = CampaignStatus.DELETED; // Create the operation. CampaignOperation operation = new CampaignOperation(); operation.operand = campaign; operation.@operator = Operator.SET; try { // Delete the campaign. CampaignReturnValue retVal = campaignService.mutate(new CampaignOperation[] {operation}); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { Campaign deletedCampaign = retVal.value[0]; Console.WriteLine("Campaign with id = \"{0}\" was renamed to \"{1}\" and deleted.", deletedCampaign.id, deletedCampaign.name); } else { Console.WriteLine("No campaigns were deleted."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to delete campaign.", 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.v201509.MediaService); try { // Create HTML5 media. byte[] html5Zip = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9Y7qI2"); // Create a media bundle containing the zip file with all the HTML5 components. Media[] mediaBundle = new Media[] { new MediaBundle() { data = html5Zip, type = MediaMediaType.MEDIA_BUNDLE }}; // Upload HTML5 zip. mediaBundle = mediaService.upload(mediaBundle); // Display HTML5 zip. if (mediaBundle != null && mediaBundle.Length > 0) { Media newBundle = mediaBundle[0]; Dictionary<MediaSize, Dimensions> dimensions = CreateMediaDimensionMap(newBundle.dimensions); Console.WriteLine("HTML5 media with id \"{0}\", dimensions \"{1}x{2}\", and MIME type " + "\"{3}\" was uploaded.", newBundle.mediaId, dimensions[MediaSize.FULL].width, dimensions[MediaSize.FULL].height, newBundle.mimeType ); } else { Console.WriteLine("No HTML5 zip was uploaded."); } } catch (Exception e) { throw new System.ApplicationException("Failed to upload HTML5 zip file.", 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; feedOperation.@operator = (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; selector.@operator = (Operator) Enum.Parse(typeof(Operator), splits[1]); } else { selector.methodName = methodName; } methodQuotaUsageList.Add(new MethodQuotaUsage(serviceName, methodName, service.get(selector).cost)); } } return methodQuotaUsageList; }
/// <summary> /// Adds the campaign targeting criteria to a campaign. /// </summary> /// <param name="user">The user.</param> /// <param name="campaignId">The campaign id.</param> /// <returns>The campaign criteria id.</returns> public long AddCampaignTargetingCriteria(AdWordsUser user, long campaignId) { // Get the CampaignCriterionService. CampaignCriterionService campaignCriterionService = (CampaignCriterionService) user.GetService( AdWordsService.v201309.CampaignCriterionService); // Create language criteria. // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html // for a detailed list of language codes. Language language1 = new Language(); language1.id = 1002; // French CampaignCriterion languageCriterion1 = new CampaignCriterion(); languageCriterion1.campaignId = campaignId; languageCriterion1.criterion = language1; CampaignCriterion[] criteria = new CampaignCriterion[] {languageCriterion1}; List<CampaignCriterionOperation> operations = new List<CampaignCriterionOperation>(); foreach (CampaignCriterion criterion in criteria) { CampaignCriterionOperation operation = new CampaignCriterionOperation(); operation.@operator = Operator.ADD; operation.operand = criterion; operations.Add(operation); } CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray()); return retVal.value[0].criterion.id; }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">The campaign ID.</param> /// <param name="videoId">The Youtube video ID.</param> public void Run(AdWordsUser user, long campaignId, string videoId) { // Get the VideoTargetingGroupService. VideoTargetingGroupService videoTargetingGroupService = (VideoTargetingGroupService) user.GetService( AdWordsService.v201406.VideoTargetingGroupService); TargetingGroup targetingGroup = new TargetingGroup(); targetingGroup.campaignId = campaignId; targetingGroup.name = "My Targeting Group " + ExampleUtilities.GetRandomString(); try { TargetingGroupOperation operation = new TargetingGroupOperation(); operation.operand = targetingGroup; operation.@operator = Operator.ADD; TargetingGroupReturnValue retval = videoTargetingGroupService.mutate( new TargetingGroupOperation[] { operation }); if (retval != null && retval.value != null && retval.value.Length > 0) { TargetingGroup newTargetingGroup = retval.value[0]; Console.WriteLine("New targeting group with id = {0}, name = {1} was created in " + "campaign id {2}", newTargetingGroup.id, newTargetingGroup.name, newTargetingGroup.campaignId); } else { Console.WriteLine("No targeting group was created."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create targeting group.", ex); } }
/// <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 = "*****@*****.**"; string password = "******"; 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> /// Adds a set of keywords to a shared set. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="sharedSetId">The shared set id.</param> /// <param name="keywordTexts">The keywords to be added to the shared set.</param> /// <returns>The newly added set of shared criteria.</returns> public SharedCriterion[] AddKeywordsToSharedSet(AdWordsUser user, long sharedSetId, string[] keywordTexts) { // Get the SharedCriterionService. SharedCriterionService sharedCriterionService = (SharedCriterionService) user.GetService(AdWordsService.v201601.SharedCriterionService); List<SharedCriterionOperation> operations = new List<SharedCriterionOperation>(); foreach (string keywordText in keywordTexts) { Keyword keyword = new Keyword(); keyword.text = keywordText; keyword.matchType = KeywordMatchType.BROAD; SharedCriterion sharedCriterion = new SharedCriterion(); sharedCriterion.criterion = keyword; sharedCriterion.negative = true; sharedCriterion.sharedSetId = sharedSetId; SharedCriterionOperation operation = new SharedCriterionOperation(); operation.@operator = Operator.ADD; operation.operand = sharedCriterion; operations.Add(operation); } SharedCriterionReturnValue retval = sharedCriterionService.mutate(operations.ToArray()); return retval.value; }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the TargetingIdeaService. TargetingIdeaService targetingIdeaService = (TargetingIdeaService) user.GetService(AdWordsService.v201406.TargetingIdeaService); // Create seed url. string url = "mars.google.com"; // Create the selector. TargetingIdeaSelector selector = new TargetingIdeaSelector(); selector.requestType = RequestType.IDEAS; selector.ideaType = IdeaType.PLACEMENT; selector.requestedAttributeTypes = new AttributeType[] {AttributeType.CRITERION, AttributeType.PLACEMENT_TYPE}; // Create related to url search parameter. RelatedToUrlSearchParameter relatedToUrlSearchParameter = new RelatedToUrlSearchParameter(); relatedToUrlSearchParameter.urls = new string[] {url}; relatedToUrlSearchParameter.includeSubUrls = false; selector.searchParameters = new SearchParameter[] {relatedToUrlSearchParameter}; // Set selector paging. selector.paging = new Paging(); int offset = 0; int pageSize = 500; TargetingIdeaPage page = new TargetingIdeaPage(); try { do { selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; // Get placement ideas. page = targetingIdeaService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (TargetingIdea idea in page.entries) { foreach (Type_AttributeMapEntry entry in idea.data) { if (entry.key == AttributeType.CRITERION) { CriterionAttribute placementAttribute = entry.value as CriterionAttribute; Placement placement = (Placement) placementAttribute.value; Console.WriteLine("Related placement urls were found at '{0}'.", (placementAttribute.value as Placement).url); } } i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of related placements found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to retrieve related placements.", ex); } }
/// <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; operation.@operator = 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); } }
/// <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 the image. Image image = new Image(); image.data = MediaUtilities.GetAssetDataFromUrl("http://goo.gl/HJM3L"); image.type = MediaMediaType.IMAGE; try { // Upload the image. Media[] result = mediaService.upload(new Media[] {image}); // Display the results. if (result != null && result.Length > 0) { Media newImage = result[0]; Dictionary<MediaSize, Dimensions> dimensions = CreateMediaDimensionMap(newImage.dimensions); Console.WriteLine("Image with id '{0}', dimensions '{1}x{2}', and MIME type '{3}'" + " was uploaded.", newImage.mediaId, dimensions[MediaSize.FULL].width, dimensions[MediaSize.FULL].height, newImage.mimeType); } else { Console.WriteLine("No images were uploaded."); } } catch (Exception e) { throw new System.ApplicationException("Failed to upload image.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="experimentId">Id of the experiment to be promoted.</param> public void Run(AdWordsUser user, long experimentId) { // Get the ExperimentService. ExperimentService experimentService = (ExperimentService) user.GetService(AdWordsService.v201406.ExperimentService); // Set experiment's status to PROMOTED. Experiment experiment = new Experiment(); experiment.id = experimentId; experiment.status = ExperimentStatus.PROMOTED; // Create the operation. ExperimentOperation operation = new ExperimentOperation(); operation.@operator = Operator.SET; operation.operand = experiment; try { // Update the experiment. ExperimentReturnValue retVal = experimentService.mutate( new ExperimentOperation[] {operation}); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { Experiment promotedExperiment = retVal.value[0]; Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was promoted.\n", promotedExperiment.name, promotedExperiment.id); } else { Console.WriteLine("No experiments were promoted."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to promote experiment.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> /// <param name="promotionId">The promotion id.</param> public void Run(AdWordsUser user, long businessId, long promotionId) { // Get the ExpressBusinessService. ExpressBusinessService businessService = (ExpressBusinessService) user.GetService(AdWordsService.v201509.ExpressBusinessService); // Get the PromotionService PromotionService promotionService = (PromotionService) user.GetService(AdWordsService.v201509.PromotionService); // Set the business ID to the service. promotionService.RequestHeader.expressBusinessId = businessId; // Update the budget for the promotion Promotion promotion = new Promotion(); promotion.id = promotionId; Money newBudget = new Money(); newBudget.microAmount = 2000000; promotion.budget = newBudget; PromotionOperation operation = new PromotionOperation(); operation.@operator = Operator.SET; operation.operand = promotion; try { Promotion[] updatedPromotions = promotionService.mutate( new PromotionOperation[] { operation }); Console.WriteLine("Promotion ID {0} for business ID {1} now has budget micro " + "amount {2}.", promotionId, businessId, updatedPromotions[0].budget.microAmount); } catch (Exception e) { throw new System.ApplicationException("Failed to update promotions.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to be removed.</param> public void Run(AdWordsUser user, long campaignId) { // Get the CampaignService. CampaignService campaignService = (CampaignService) user.GetService( AdWordsService.v201406.CampaignService); // Create campaign with REMOVED status. Campaign campaign = new Campaign(); campaign.id = campaignId; // When removing a campaign, rename it to avoid name collisions with new // campaigns. campaign.name = "Removed Campaign - " + ExampleUtilities.GetRandomString(); campaign.status = CampaignStatus.REMOVED; // Create the operation. CampaignOperation operation = new CampaignOperation(); operation.operand = campaign; operation.@operator = Operator.SET; try { // Remove the campaign. CampaignReturnValue retVal = campaignService.mutate(new CampaignOperation[] {operation}); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { Campaign removedCampaign = retVal.value[0]; Console.WriteLine("Campaign with id = \"{0}\" was renamed to \"{1}\" and removed.", removedCampaign.id, removedCampaign.name); } else { Console.WriteLine("No campaigns were removed."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to remove campaign.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to be updated.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService) user.GetService(AdWordsService.v201402.AdGroupService); // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.status = AdGroupStatus.PAUSED; adGroup.id = adGroupId; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.SET; operation.operand = adGroup; try { // Update the ad group. AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] {operation}); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroup pausedAdGroup = retVal.value[0]; Console.WriteLine("Ad group with id = '{0}' was successfully updated.", pausedAdGroup.id); } else { Console.WriteLine("No ad groups were updated."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to update ad group.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the ManagedCustomerService. ManagedCustomerService managedCustomerService = (ManagedCustomerService) user.GetService( AdWordsService.v201406.ManagedCustomerService); // Create account. ManagedCustomer customer = new ManagedCustomer(); customer.name = "Customer created with ManagedCustomerService on " + new DateTime().ToString(); customer.currencyCode = "EUR"; customer.dateTimeZone = "Europe/London"; // Create operations. ManagedCustomerOperation operation = new ManagedCustomerOperation(); operation.operand = customer; operation.@operator = Operator.ADD; try { ManagedCustomerOperation[] operations = new ManagedCustomerOperation[] {operation}; // Add account. ManagedCustomerReturnValue result = managedCustomerService.mutate(operations); // Display accounts. if (result.value != null && result.value.Length > 0) { ManagedCustomer customerResult = result.value[0]; Console.WriteLine("Account with customer ID \"{0}\" was created.", customerResult.customerId); } else { Console.WriteLine("No accounts were created."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create accounts.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which keywords are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService) user.GetService( AdWordsService.v201509.AdGroupCriterionService); List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>(); foreach (string keywordText in KEYWORDS) { // Create the keyword. Keyword keyword = new Keyword(); keyword.text = keywordText; keyword.matchType = KeywordMatchType.BROAD; // Create the biddable ad group criterion. BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion(); keywordCriterion.adGroupId = adGroupId; keywordCriterion.criterion = keyword; // Optional: Set the user status. keywordCriterion.userStatus = UserStatus.PAUSED; // Optional: Set the keyword destination url. keywordCriterion.finalUrls = new UrlList() { urls = new string[] { "http://example.com/mars/cruise/?kw=" + HttpUtility.UrlEncode(keywordText) } }; // Create the operations. AdGroupCriterionOperation operation = new AdGroupCriterionOperation(); operation.@operator = Operator.ADD; operation.operand = keywordCriterion; operations.Add(operation); } try { // Create the keywords. AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null) { foreach (AdGroupCriterion adGroupCriterion in retVal.value) { // If you are adding multiple type of criteria, then you may need to // check for // // if (adGroupCriterion is Keyword) { ... } // // to identify the criterion type. Console.WriteLine("Keyword with ad group id = '{0}', keyword id = '{1}', text = " + "'{2}' and match type = '{3}' was created.", adGroupCriterion.adGroupId, adGroupCriterion.criterion.id, (adGroupCriterion.criterion as Keyword).text, (adGroupCriterion.criterion as Keyword).matchType); } } else { Console.WriteLine("No keywords were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create keywords.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to be updated.</param> public void Run(AdWordsUser user, long campaignId) { // Get the CampaignService. CampaignService campaignService = (CampaignService)user.GetService(AdWordsService.v201402.CampaignService); // Create the campaign. Campaign campaign = new Campaign(); campaign.id = campaignId; campaign.status = CampaignStatus.PAUSED; // Create the operation. CampaignOperation operation = new CampaignOperation(); operation.@operator = Operator.SET; operation.operand = campaign; try { // Update the campaign. CampaignReturnValue retVal = campaignService.mutate((new CampaignOperation[] {operation})); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { Campaign updatedCampaign = retVal.value[0]; Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was updated.", updatedCampaign.name, updatedCampaign.id); } else { Console.WriteLine("No campaigns were updated."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to update campaign.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> public void Run(AdWordsUser user, long businessId) { // Get the ExpressBusinessService. ExpressBusinessService businessService = (ExpressBusinessService) user.GetService(AdWordsService.v201406.ExpressBusinessService); // Update the website and address for the business ExpressBusiness business = new ExpressBusiness(); business.id = businessId; business.name = "Express Interplanetary Cruise #" + ExampleUtilities.GetShortRandomString(); business.website = "http://www.example.com/?myParam=" + businessId; ExpressBusinessOperation operation = new ExpressBusinessOperation(); operation.@operator = Operator.SET; operation.operand = business; try { ExpressBusiness[] updatedBusinesses = businessService.mutate(new ExpressBusinessOperation[] { operation }); Console.WriteLine("Express business with ID {0} and name '{1}' was updated.", updatedBusinesses[0].id, updatedBusinesses[0].name); } catch (Exception ex) { throw new System.ApplicationException("Failed to update express business.", ex); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> public void Run(AdWordsUser user) { // Get the AlertService. AlertService alertService = (AlertService) user.GetService( AdWordsService.v201402.AlertService); // Create the selector. AlertSelector selector = new AlertSelector(); // Create the alert query. AlertQuery query = new AlertQuery(); query.filterSpec = FilterSpec.ALL; query.clientSpec = ClientSpec.ALL; query.triggerTimeSpec = TriggerTimeSpec.ALL_TIME; query.severities = new AlertSeverity[] {AlertSeverity.GREEN, AlertSeverity.YELLOW, AlertSeverity.RED}; // Enter all possible values of AlertType to get all alerts. If you are // interested only in specific alert types, then you may also do it as // follows: // query.types = new AlertType[] {AlertType.CAMPAIGN_ENDING, // AlertType.CAMPAIGN_ENDED}; query.types = (AlertType[]) Enum.GetValues(typeof(AlertType)); selector.query = query; // Set paging for selector. selector.paging = new Paging(); int offset = 0; int pageSize = 500; AlertPage page = new AlertPage(); try { do { // Get account alerts. selector.paging.startIndex = offset; selector.paging.numberResults = pageSize; page = alertService.get(selector); // Display the results. if (page != null && page.entries != null) { int i = offset; foreach (Alert alert in page.entries) { Console.WriteLine("{0}) Customer Id is {1:###-###-####}, Alert type is '{2}', " + "Severity is {3}", i + 1, alert.clientCustomerId, alert.alertType, alert.alertSeverity); for (int j = 0; j < alert.details.Length; j++) { Console.WriteLine(" - Triggered at {0}", alert.details[j].triggerTime); } i++; } } offset += pageSize; } while (offset < page.totalNumEntries); Console.WriteLine("Number of alerts found: {0}", page.totalNumEntries); } catch (Exception ex) { throw new System.ApplicationException("Failed to retrieve alerts.", 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) { ReportDefinition definition = new ReportDefinition(); definition.reportName = "Last 7 days CRITERIA_PERFORMANCE_REPORT"; definition.reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT; definition.downloadFormat = DownloadFormat.GZIPPED_CSV; definition.dateRangeType = ReportDefinitionDateRangeType.LAST_7_DAYS; // Create selector. Selector selector = new Selector(); selector.fields = new string[] {"CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria", "FinalUrls", "Clicks", "Impressions", "Cost"}; Predicate predicate = new Predicate(); predicate.field = "Status"; predicate.@operator = PredicateOperator.IN; predicate.values = new string[] {"ENABLED", "PAUSED"}; selector.predicates = new Predicate[] {predicate}; definition.selector = selector; definition.includeZeroImpressions = true; string filePath = ExampleUtilities.GetHomeDir() + Path.DirectorySeparatorChar + fileName; try { ReportUtilities utilities = new ReportUtilities(user, "v201409", definition); using (ReportResponse response = utilities.GetResponse()) { response.Save(filePath); } Console.WriteLine("Report was downloaded to '{0}'.", filePath); } catch (Exception ex) { throw new System.ApplicationException("Failed to download report.", ex); } }