/// <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);
      }
    }
    /// <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.v201409.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 ex) {
        throw new System.ApplicationException("Failed to get images and videos.", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign for which disapproved ads
    /// are retrieved.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the AdGroupAdService.
      AdGroupAdService service =
          (AdGroupAdService) user.GetService(AdWordsService.v201409.AdGroupAdService);

      // Create the selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"Id", "AdGroupCreativeApprovalStatus",
          "AdGroupAdDisapprovalReasons"};

      // Create the filter.
      Predicate campaignPredicate = new Predicate();
      campaignPredicate.@operator = PredicateOperator.EQUALS;
      campaignPredicate.field = "CampaignId";
      campaignPredicate.values = new string[] {campaignId.ToString()};

      Predicate approvalPredicate = new Predicate();
      approvalPredicate.@operator = PredicateOperator.EQUALS;
      approvalPredicate.field = "AdGroupCreativeApprovalStatus";
      approvalPredicate.values = new string[] {AdGroupAdApprovalStatus.DISAPPROVED.ToString()};

      selector.predicates = new Predicate[] {campaignPredicate, approvalPredicate};

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      AdGroupAdPage page = new AdGroupAdPage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get the disapproved ads.
          page = service.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;
            foreach (AdGroupAd adGroupAd in page.entries) {
              Console.WriteLine("{0}) Ad id {1} has been disapproved for the following " +
                  "reason(s):", i, adGroupAd.ad.id);
              foreach (string reason in adGroupAd.disapprovalReasons) {
                Console.WriteLine("    {0}", reason);
              }
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of disapproved ads found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to get disapproved ads.", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign from which targeting
    /// criteria are retrieved.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201409.CampaignCriterionService);

      // Create the selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"Id", "CriteriaType", "PlacementUrl"};

      // Set the filters.
      Predicate campaignPredicate = new Predicate();
      campaignPredicate.field = "CampaignId";
      campaignPredicate.@operator = PredicateOperator.EQUALS;
      campaignPredicate.values = new string[] {campaignId.ToString()};

      Predicate placementPredicate = new Predicate();
      placementPredicate.field = "CriteriaType";
      placementPredicate.@operator = PredicateOperator.EQUALS;
      placementPredicate.values = new string[] {"PLACEMENT"};

      selector.predicates = new Predicate[] {campaignPredicate, placementPredicate};

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      CampaignCriterionPage page = new CampaignCriterionPage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get all campaign targets.
          page = campaignCriterionService.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;
            foreach (CampaignCriterion campaignCriterion in page.entries) {
              Placement placement = campaignCriterion.criterion as Placement;

              Console.WriteLine("{0}) Placement with ID {1} and url {2} was found.", i,
                  placement.id, placement.url);
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of placements found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to get campaign targeting criteria.", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="labelName">ID of the label.</param>
    public void Run(AdWordsUser user, long labelId) {
      // Get the CampaignService.
      CampaignService campaignService =
          (CampaignService) user.GetService(AdWordsService.v201409.CampaignService);

      // Create the selector.
      Selector selector = new Selector();
      selector.fields = new string[] { "Id", "Name", "Labels" };

      // Labels filtering is performed by ID. You can use CONTAINS_ANY to
      // select campaigns with any of the label IDs, CONTAINS_ALL to select
      // campaigns with all of the label IDs, or CONTAINS_NONE to select
      // campaigns with none of the label IDs.
      Predicate predicate = new Predicate();
      predicate.@operator = PredicateOperator.CONTAINS_ANY;
      predicate.field = "Labels";
      predicate.values = new string[] { labelId.ToString() };
      selector.predicates = new Predicate[] { predicate };

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      CampaignPage page = new CampaignPage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get the campaigns.
          page = campaignService.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;
            foreach (Campaign campaign in page.entries) {
              List<string> labelNames = new List<string>();
              foreach (Label label in campaign.labels) {
                labelNames.Add(label.name);
              }

              Console.WriteLine("{0}) Campaign with id = '{1}', name = '{2}' and labels = '{3}'" +
                  " was found.", i + 1, campaign.id, campaign.name,
                  string.Join(", ", labelNames.ToArray()));
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of campaigns found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to retrieve campaigns by label", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group to which ads are added.
    /// </param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the AdGroupAdService.
      AdGroupBidModifierService adGroupBidModifierService =
          (AdGroupBidModifierService) user.GetService(
              AdWordsService.v201409.AdGroupBidModifierService);

      const int PAGE_SIZE = 500;

      // Get all ad group bid modifiers for the campaign.
      Selector selector = new Selector();
      selector.fields = new String[] {"CampaignId", "AdGroupId", "BidModifier", "BidModifierSource",
        "CriteriaType", "Id"};

      Predicate predicate = new Predicate();
      predicate.field = "CampaignId";
      predicate.@operator = PredicateOperator.EQUALS;
      predicate.values = new string[] {campaignId.ToString()};
      selector.predicates = new Predicate[] {predicate};

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = PAGE_SIZE;

      AdGroupBidModifierPage page = new AdGroupBidModifierPage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get the campaigns.
          page = adGroupBidModifierService.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;
            foreach (AdGroupBidModifier adGroupBidModifier in page.entries) {
              string bidModifier = (adGroupBidModifier.bidModifierSpecified)?
                  adGroupBidModifier.bidModifier.ToString() : "UNSET";
              Console.WriteLine("{0}) Campaign ID {1}, AdGroup ID {2}, Criterion ID {3} has " +
                  "ad group level modifier: {4} and source = {5}.",
                  i + 1, adGroupBidModifier.campaignId,
                  adGroupBidModifier.adGroupId, adGroupBidModifier.criterion.id, bidModifier,
                  adGroupBidModifier.bidModifierSource);
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of adgroup bid modifiers found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to retrieve adgroup bid modifiers.", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      // Get the ExpressBusinessService.
      ExpressBusinessService businessService = (ExpressBusinessService)
          user.GetService(AdWordsService.v201409.ExpressBusinessService);

      Selector selector = new Selector();
      selector.fields = new String[] { "Id", "Name", "Website", "Address", "GeoPoint", "Status" };

      // To get all express businesses owned by the current customer,
      // simply skip the call to selector.setPredicates below.
      Predicate predicate = new Predicate();
      predicate.field = "Status";
      predicate.@operator = PredicateOperator.EQUALS;
      predicate.values = new string[] { "ACTIVE" };

      selector.predicates = new Predicate[] { predicate };

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      ExpressBusinessPage page = null;
      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get all businesses.
          page = businessService.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;
            foreach (ExpressBusiness business in page.entries) {
              Console.WriteLine("{0}) Express business found with name '{1}', id = {2}, " +
                  "website = {3} and status = {4}.\n", i + 1, business.name, business.id,
                  business.website, business.status);
              Console.WriteLine("Address");
              Console.WriteLine("=======");
              Console.WriteLine(FormatAddress(business.address));
              Console.WriteLine("Co-ordinates: {0}\n", FormatGeopoint(business.geoPoint));
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of businesses found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to retrieve express business.", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="productServiceSuggestion">The product/service suggestion.
    /// </param>
    /// <param name="localeText">The locale text.</param>
    public void Run(AdWordsUser user, string productServiceSuggestion, string localeText) {
      // Get the service, which loads the required classes.
      ProductServiceService productServiceService = (ProductServiceService) user.GetService(
          AdWordsService.v201409.ProductServiceService);

      // Create selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"ProductServiceText"};

      // Create predicates.
      Predicate textPredicate = new Predicate();
      textPredicate.field = "ProductServiceText";
      textPredicate.@operator = PredicateOperator.EQUALS;
      textPredicate.values = new string[] {productServiceSuggestion};

      Predicate localePredicate = new Predicate();
      localePredicate.field = "Locale";
      localePredicate.@operator = PredicateOperator.EQUALS;
      localePredicate.values = new string[]{localeText};

      selector.predicates = new Predicate[] {textPredicate, localePredicate};

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      ProductServicePage page = null;
      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Make the get request.
          page = productServiceService.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;
            foreach (ProductService productService in page.entries) {
              Console.WriteLine("Product/service with text '{0}' found", productService.text);
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of products/services found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to retrieve products/services.", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      // Get the LocationCriterionService.
      LocationCriterionService locationCriterionService =
          (LocationCriterionService) user.GetService(AdWordsService.v201409.
              LocationCriterionService);

      string[] locationNames = new string[] {"Paris", "Quebec", "Spain", "Deutschland"};

      Selector selector = new Selector();
      selector.fields = new string[] {"Id", "LocationName", "CanonicalName", "DisplayType",
          "ParentLocations", "Reach", "TargetingStatus"};

      // Location names must match exactly, only EQUALS and IN are supported.
      Predicate predicate1 = new Predicate();
      predicate1.field = "LocationName";
      predicate1.@operator = PredicateOperator.IN;
      predicate1.values = locationNames;

      // Set the locale of the returned location names.
      Predicate predicate2 = new Predicate();
      predicate2.field = "Locale";
      predicate2.@operator = PredicateOperator.EQUALS;
      predicate2.values = new string[] {"en"};

      selector.predicates = new Predicate[] {predicate1, predicate2};

      try {
        // Make the get request.
        LocationCriterion[] locationCriteria = locationCriterionService.get(selector);

        // Display the resulting location criteria.
        foreach (LocationCriterion locationCriterion in locationCriteria) {
          string parentLocations = "";
          if (locationCriterion.location != null &&
              locationCriterion.location.parentLocations != null) {
            foreach (Location location in locationCriterion.location.parentLocations) {
              parentLocations += GetLocationString(location) + ", ";
            }
            parentLocations.TrimEnd(',', ' ');
          } else {
            parentLocations = "N/A";
          }
          Console.WriteLine("The search term '{0}' returned the location '{1}' of type '{2}' " +
              "with parent locations '{3}',  reach '{4}' and targeting status '{5}.",
              locationCriterion.searchTerm, locationCriterion.location.locationName,
              locationCriterion.location.displayType, parentLocations, locationCriterion.reach,
              locationCriterion.location.targetingStatus);
        }
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to get location criteria.", ex);
      }
    }
예제 #10
0
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign for which ad groups are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the AdGroupService.
      AdGroupService adGroupService =
          (AdGroupService) user.GetService(AdWordsService.v201409.AdGroupService);

      // Create the selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"Id", "Name"};

      // Create the filters.
      Predicate predicate = new Predicate();
      predicate.field = "CampaignId";
      predicate.@operator = PredicateOperator.EQUALS;
      predicate.values = new string[] {campaignId.ToString()};
      selector.predicates = new Predicate[] {predicate};

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      AdGroupPage page = new AdGroupPage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get the ad groups.
          page = adGroupService.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;
            foreach (AdGroup adGroup in page.entries) {
              Console.WriteLine("{0}) Ad group name is '{1}' and id is {2}.", i + 1, adGroup.name,
                  adGroup.id);
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of ad groups found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to retrieve ad groups.", ex);
      }
    }
    /// <summary>
    /// Runs the specified user.
    /// </summary>
    /// <param name="user">The user.</param>
    /// <param name="adGroupId">Id of the ad group for which bid simulations are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the DataService.
      DataService dataService = (DataService) user.GetService(AdWordsService.v201409.DataService);

      // Create the selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"AdGroupId", "LandscapeType", "LandscapeCurrent", "StartDate",
          "EndDate", "Bid", "LocalClicks", "LocalCost", "MarginalCpc", "LocalImpressions"};

      // Set the filters.
      Predicate adGroupPredicate = new Predicate();
      adGroupPredicate.field = "AdGroupId";
      adGroupPredicate.@operator = PredicateOperator.IN;
      adGroupPredicate.values = new string[] {adGroupId.ToString()};

      selector.predicates = new Predicate[] {adGroupPredicate};

      try {
        // Get bid landscape for ad group.
        AdGroupBidLandscapePage page = dataService.getAdGroupBidLandscape(selector);
        if (page != null && page.entries != null && page.entries.Length > 0) {
          foreach (AdGroupBidLandscape bidLandscape in page.entries) {
            Console.WriteLine("Found ad group bid landscape with ad group id '{0}', type '{1}', " +
                "current: '{2}', start date '{3}', end date '{4}', and landscape points",
                bidLandscape.adGroupId, bidLandscape.type, bidLandscape.landscapeCurrent,
                bidLandscape.startDate, bidLandscape.endDate);
            foreach (BidLandscapeLandscapePoint point in bidLandscape.landscapePoints) {
              Console.WriteLine("- bid: {0} => clicks: {1}, cost: {2}, marginalCpc: {3}, " +
                  "impressions: {4}", point.bid.microAmount, point.bid.microAmount,
                  point.clicks, point.cost.microAmount, point.marginalCpc.microAmount,
                  point.impressions);
            }
          }
        } else {
          Console.WriteLine("No ad group bid landscapes were found.");
        }
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to get ad group bid landscapes.", ex);
      }
    }
예제 #12
0
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(
              AdWordsService.v201409.AdGroupCriterionService);

      // Create a selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"Id", "AdGroupId", "PlacementUrl"};

      // Select only keywords.
      Predicate predicate = new Predicate();
      predicate.field = "CriteriaType";
      predicate.@operator = PredicateOperator.EQUALS;
      predicate.values = new string[] {"PLACEMENT"};
      selector.predicates = new Predicate[] {predicate};

      // Set the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      AdGroupCriterionPage page = new AdGroupCriterionPage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get the keywords.
          page = adGroupCriterionService.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;

            foreach (AdGroupCriterion adGroupCriterion in page.entries) {
              bool isNegative = (adGroupCriterion is NegativeAdGroupCriterion);

              // If you are retrieving multiple type of criteria, then you may
              // need to check for
              //
              // if (adGroupCriterion is Placement) { ... }
              //
              // to identify the criterion type.
              Placement placement = (Placement) adGroupCriterion.criterion;
              if (isNegative) {
                Console.WriteLine("{0}) Negative placement with ad group ID = '{1}', placement " +
                    "ID = '{2}', and url = '{3}' was found.", i, adGroupCriterion.adGroupId,
                    placement.id, placement.url);
              } else {
                Console.WriteLine("{0}) Placement with ad group ID = '{1}', placement ID = '{2}' " +
                    "and url = '{3}' was found.", i, adGroupCriterion.adGroupId,
                    placement.id, placement.url);
              }
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of placements found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to retrieve placements.");
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group for which keyword bid
    /// simulations are retrieved.</param>
    /// <param name="keywordId">Id of the keyword for which bid simulations are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long adGroupId, long keywordId) {
      // Get the DataService.
      DataService dataService = (DataService) user.GetService(AdWordsService.v201409.DataService);

      // Create the selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"AdGroupId", "CriterionId", "StartDate", "EndDate", "Bid",
          "LocalClicks", "LocalCost", "MarginalCpc", "LocalImpressions"};

      // Create the filters.
      Predicate adGroupPredicate = new Predicate();
      adGroupPredicate.field = "AdGroupId";
      adGroupPredicate.@operator = PredicateOperator.IN;
      adGroupPredicate.values = new string[] {adGroupId.ToString()};

      Predicate keywordPredicate = new Predicate();
      keywordPredicate.field = "CriterionId";
      keywordPredicate.@operator = PredicateOperator.IN;
      keywordPredicate.values = new string[] {keywordId.ToString()};

      selector.predicates = new Predicate[] {adGroupPredicate, keywordPredicate};

      // Set selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      CriterionBidLandscapePage page = new CriterionBidLandscapePage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get bid landscape for keywords.
          page = dataService.getCriterionBidLandscape(selector);

          // Display bid landscapes.
          if (page != null && page.entries != null) {
            int i = offset;

            foreach (CriterionBidLandscape bidLandscape in page.entries) {
              Console.WriteLine("{0}) Found criterion bid landscape with ad group id '{1}', " +
                  "keyword id '{2}', start date '{3}', end date '{4}', and landscape points:",
                  i, bidLandscape.adGroupId, bidLandscape.criterionId, bidLandscape.startDate,
                  bidLandscape.endDate);
              foreach (BidLandscapeLandscapePoint bidLandscapePoint in
                  bidLandscape.landscapePoints) {
                Console.WriteLine("- bid: {0} => clicks: {1}, cost: {2}, marginalCpc: {3}, " +
                    "impressions: {4}\n", bidLandscapePoint.bid.microAmount,
                    bidLandscapePoint.clicks, bidLandscapePoint.cost.microAmount,
                    bidLandscapePoint.marginalCpc.microAmount, bidLandscapePoint.impressions);
              }
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of keyword bid landscapes found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to retrieve keyword bid landscapes.", ex);
      }
    }
예제 #14
0
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      // Get the UserListService.
      AdwordsUserListService userListService =
          (AdwordsUserListService) user.GetService(AdWordsService.v201409.AdwordsUserListService);

      // Get the ConversionTrackerService.
      ConversionTrackerService conversionTrackerService =
          (ConversionTrackerService)user.GetService(AdWordsService.v201409.
              ConversionTrackerService);

      BasicUserList userList = new BasicUserList();
      userList.name = "Mars cruise customers #" + ExampleUtilities.GetRandomString();
      userList.description = "A list of mars cruise customers in the last year.";
      userList.status = UserListMembershipStatus.OPEN;
      userList.membershipLifeSpan = 365;

      UserListConversionType conversionType = new UserListConversionType();
      conversionType.name = userList.name;
      userList.conversionTypes = new UserListConversionType[] {conversionType};

      // Optional: Set the user list status.
      userList.status = UserListMembershipStatus.OPEN;

      // Create the operation.
      UserListOperation operation = new UserListOperation();
      operation.operand = userList;
      operation.@operator = Operator.ADD;

      try {
        // Add the user list.
        UserListReturnValue retval = userListService.mutate(new UserListOperation[] {operation});

        UserList[] userLists = null;
        if (retval != null && retval.value != null) {
          userLists = retval.value;
          // Get all conversion snippets
          List<string> conversionIds = new List<string>();
          foreach (BasicUserList newUserList in userLists) {
            if (newUserList.conversionTypes != null) {
              foreach (UserListConversionType newConversionType in newUserList.conversionTypes) {
                conversionIds.Add(newConversionType.id.ToString());
              }
            }
          }

          Dictionary<long, ConversionTracker> conversionsMap =
              new Dictionary<long, ConversionTracker>();

          if (conversionIds.Count > 0) {
            // Create the selector.
            Selector selector = new Selector();
            selector.fields = new string[] {"Id"};

            Predicate conversionTypePredicate = new Predicate();
            conversionTypePredicate.field = "Id";
            conversionTypePredicate.@operator = PredicateOperator.IN;
            conversionTypePredicate.values = conversionIds.ToArray();
            selector.predicates = new Predicate[] {conversionTypePredicate};

            // Get all conversion trackers.
            ConversionTrackerPage page = conversionTrackerService.get(selector);

            if (page != null && page.entries != null) {
              foreach (ConversionTracker tracker in page.entries) {
                conversionsMap[tracker.id] = tracker;
              }
            }
          }

          // Display the results.
          foreach (BasicUserList newUserList in userLists) {
            Console.WriteLine("User list with name '{0}' and id '{1}' was added.",
                newUserList.name, newUserList.id);

            // Display user list associated conversion code snippets.
            if (newUserList.conversionTypes != null) {
              foreach (UserListConversionType userListConversionType in
                  newUserList.conversionTypes) {
                if (conversionsMap.ContainsKey(userListConversionType.id)) {
                  AdWordsConversionTracker conversionTracker =
                      (AdWordsConversionTracker) conversionsMap[userListConversionType.id];
                  Console.WriteLine("Conversion type code snippet associated to the list:\n{0}\n",
                      conversionTracker.snippet);
                } else {
                  throw new Exception("Failed to associate conversion type code snippet.");
                }
              }
            }
          }
        } else {
          Console.WriteLine("No user lists (a.k.a. audiences) were added.");
        }
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to add user lists (a.k.a. audiences).", ex);
      }
    }
예제 #15
0
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group from which text ads are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      // Get the AdGroupAdService.
      AdGroupAdService service =
          (AdGroupAdService) user.GetService(AdWordsService.v201409.AdGroupAdService);

      // Create a selector.
      Selector selector = new Selector();
      selector.fields = new string[] {"Id", "Status", "Headline", "Description1", "Description2",
          "DisplayUrl"};

      // Set the sort order.
      OrderBy orderBy = new OrderBy();
      orderBy.field = "Id";
      orderBy.sortOrder = SortOrder.ASCENDING;
      selector.ordering = new OrderBy[] {orderBy};

      // Restrict the fetch to only the selected ad group id.
      Predicate adGroupPredicate = new Predicate();
      adGroupPredicate.field = "AdGroupId";
      adGroupPredicate.@operator = PredicateOperator.EQUALS;
      adGroupPredicate.values = new string[] {adGroupId.ToString()};

      // Retrieve only text ads.
      Predicate typePredicate = new Predicate();
      typePredicate.field = "AdType";
      typePredicate.@operator = PredicateOperator.EQUALS;
      typePredicate.values = new string[] {"TEXT_AD"};

      // By default disabled ads aren't returned by the selector. To return
      // them include the DISABLED status in the statuses field.
      Predicate statusPredicate = new Predicate();
      statusPredicate.field = "Status";
      statusPredicate.@operator = PredicateOperator.IN;

      statusPredicate.values = new string[] {AdGroupAdStatus.ENABLED.ToString(),
          AdGroupAdStatus.PAUSED.ToString(), AdGroupAdStatus.DISABLED.ToString()};

      selector.predicates = new Predicate[] {adGroupPredicate, statusPredicate, typePredicate};

      // Select the selector paging.
      selector.paging = new Paging();

      int offset = 0;
      int pageSize = 500;

      AdGroupAdPage page = new AdGroupAdPage();

      try {
        do {
          selector.paging.startIndex = offset;
          selector.paging.numberResults = pageSize;

          // Get the text ads.
          page = service.get(selector);

          // Display the results.
          if (page != null && page.entries != null) {
            int i = offset;

            foreach (AdGroupAd adGroupAd in page.entries) {
              TextAd textAd = (TextAd) adGroupAd.ad;
              Console.WriteLine("{0}) Ad id is {1} and status is {2}", i + 1, textAd.id,
                  adGroupAd.status);
              Console.WriteLine("  {0}\n  {1}\n  {2}\n  {3}", textAd.headline,
                  textAd.description1, textAd.description2, textAd.displayUrl);
              i++;
            }
          }
          offset += pageSize;
        } while (offset < page.totalNumEntries);
        Console.WriteLine("Number of text ads found: {0}", page.totalNumEntries);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to get text ads", ex);
      }
    }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      // Get the ConstantDataService.
      ConstantDataService constantDataService = (ConstantDataService) user.GetService(
          AdWordsService.v201409.ConstantDataService);

      Selector selector = new Selector();
      Predicate predicate = new Predicate();
      predicate.field = "Country";
      predicate.@operator = PredicateOperator.IN;
      predicate.values = new string[] { "US" };

      try {
        ProductBiddingCategoryData[] results =
            constantDataService.getProductBiddingCategoryData(selector);

        Dictionary<long, ProductCategory> biddingCategories =
            new Dictionary<long, ProductCategory>();
        List<ProductCategory> rootCategories = new List<ProductCategory>();

        foreach (ProductBiddingCategoryData productBiddingCategory in results) {
          long id = productBiddingCategory.dimensionValue.value;
          long parentId = 0;
          string name = productBiddingCategory.displayValue[0].value;

          if (productBiddingCategory.parentDimensionValue != null) {
            parentId = productBiddingCategory.parentDimensionValue.value;
          }

          if (biddingCategories.ContainsKey(id)) {
            biddingCategories.Add(id, new ProductCategory());
          }

          ProductCategory category = biddingCategories[id];

          if (parentId != 0) {
            if (biddingCategories.ContainsKey(parentId)) {
              biddingCategories.Add(parentId, new ProductCategory());
            }
            ProductCategory parent = biddingCategories[parentId];
            parent.Children.Add(category);
          } else {
            rootCategories.Add(category);
          }

          category.Id = id;
          category.Name = name;
        }

        DisplayProductCategories(rootCategories, "");
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to set shopping product category.", ex);
      }
    }
예제 #17
0
    /// <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.v201409.ExpressBusinessService);

      // Get the PromotionService
      PromotionService promotionService = (PromotionService)
          user.GetService(AdWordsService.v201409.PromotionService);

      // Get the business for the businessId. We will need its geo point to
      // create a Proximity criterion for the new Promotion.
      Selector businessSelector = new Selector();

      Predicate predicate = new Predicate();
      predicate.field = "Id";
      predicate.@operator = PredicateOperator.EQUALS;
      predicate.values = new string[] { businessId.ToString() };
      businessSelector.predicates = new Predicate[] { predicate };

      businessSelector.fields = new string[] { "Id", "GeoPoint" };

      ExpressBusinessPage businessPage = businessService.get(businessSelector);

      if (businessPage == null || businessPage.entries == null ||
          businessPage.entries.Length == 0) {
        Console.WriteLine("No business was found.");
        return;
      }

      // Set the business ID to the service.
      promotionService.RequestHeader.expressBusinessId = businessId;

      // First promotion
      Promotion marsTourPromotion = new Promotion();
      Money budget = new Money();
      budget.microAmount = 1000000L;
      marsTourPromotion.name = "Mars Tour Promotion " + ExampleUtilities.GetShortRandomString();
      marsTourPromotion.status = PromotionStatus.PAUSED;
      marsTourPromotion.destinationUrl = "http://www.example.com";
      marsTourPromotion.budget = budget;
      marsTourPromotion.callTrackingEnabled = true;

      // Criteria

      // Criterion - Travel Agency product service
      ProductService productService = new ProductService();
      productService.text = "Travel Agency";

      // Criterion - English language
      // The ID can be found in the documentation:
      // https://developers.google.com/adwords/api/docs/appendix/languagecodes
      Language language = new Language();
      language.id = 1000L;

      // Criterion - Within 15 miles
      Proximity proximity = new Proximity();
      proximity.geoPoint = businessPage.entries[0].geoPoint;
      proximity.radiusDistanceUnits = ProximityDistanceUnits.MILES;
      proximity.radiusInUnits = 15;

      marsTourPromotion.criteria = new Criterion[] { productService, language, proximity };

      // Creative
      Creative creative = new Creative();
      creative.headline = "Standard Mars Trip";
      creative.line1 = "Fly coach to Mars";
      creative.line2 = "Free in-flight pretzels";

      marsTourPromotion.creatives = new Creative[] { creative };

      PromotionOperation operation = new PromotionOperation();
      operation.@operator = Operator.ADD;
      operation.operand = marsTourPromotion;

      try {
        Promotion[] addedPromotions = promotionService.mutate(
            new PromotionOperation[] { operation });

        Console.WriteLine("Added promotion ID {0} with name {1} to business ID {2}.",
        addedPromotions[0].id, addedPromotions[0].name, businessId);
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to add promotions.", ex);
      }
    }
예제 #18
0
    /// <summary>
    /// Gets the ad group ad by ID.
    /// </summary>
    /// <param name="adGroupAdService">The AdGroupAdService instance.</param>
    /// <param name="adGroupId">ID of the ad group.</param>
    /// <param name="adId">ID of the ad to be retrieved.</param>
    /// <returns>The AdGroupAd if the item could be retrieved, null otherwise.
    /// </returns>
    private AdGroupAd GetAdGroupAd(AdGroupAdService adGroupAdService, long adGroupId, long adId) {
      // Create a selector.
      Selector selector = new Selector();
      selector.fields = new string[] { "Id", "Url" };

      // Restrict the fetch to only the selected ad group ID and ad ID.
      Predicate adGroupPredicate = new Predicate();
      adGroupPredicate.field = "AdGroupId";
      adGroupPredicate.@operator = PredicateOperator.EQUALS;
      adGroupPredicate.values = new string[] { adGroupId.ToString() };

      Predicate adPredicate = new Predicate();
      adPredicate.field = "Id";
      adPredicate.@operator = PredicateOperator.EQUALS;
      adPredicate.values = new string[] { adId.ToString() };

      selector.predicates = new Predicate[] { adGroupPredicate, adPredicate };

      // Get the ad.
      AdGroupAdPage page = adGroupAdService.get(selector);

      if (page != null && page.entries != null && page.entries.Length > 0) {
        return page.entries[0];
      } else {
        return null;
      }
    }