/// <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.v201601.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="baseCampaignId">Id of the campaign to use as base of the
        /// draft.</param>
        public void Run(AdWordsUser user, long baseCampaignId)
        {
            using (DraftService draftService = (DraftService)user.GetService(
                       AdWordsService.v201802.DraftService))
                using (CampaignCriterionService campaignCriterionService =
                           (CampaignCriterionService)user.GetService(
                               AdWordsService.v201802.CampaignCriterionService)) {
                    Draft draft = new Draft()
                    {
                        baseCampaignId = baseCampaignId,
                        draftName      = "Test Draft #" + ExampleUtilities.GetRandomString()
                    };

                    DraftOperation draftOperation = new DraftOperation()
                    {
                        @operator = Operator.ADD,
                        operand   = draft
                    };

                    try {
                        draft = draftService.mutate(new DraftOperation[] { draftOperation }).value[0];

                        Console.WriteLine("Draft with ID {0}, base campaign ID {1} and draft campaign ID " +
                                          "{2} created.", draft.draftId, draft.baseCampaignId, draft.draftCampaignId);

                        // Once the draft is created, you can modify the draft campaign as if it
                        // were a real campaign. For example, you may add criteria, adjust bids,
                        // or even include additional ads. Adding a criterion is shown here.

                        Language language = new Language()
                        {
                            id = 1003L // Spanish
                        };

                        // Make sure to use the draftCampaignId when modifying the virtual draft
                        // campaign.
                        CampaignCriterion campaignCriterion = new CampaignCriterion()
                        {
                            campaignId = draft.draftCampaignId,
                            criterion  = language
                        };

                        CampaignCriterionOperation criterionOperation = new CampaignCriterionOperation()
                        {
                            @operator = Operator.ADD,
                            operand   = campaignCriterion
                        };

                        campaignCriterion = campaignCriterionService.mutate(
                            new CampaignCriterionOperation[] { criterionOperation }).value[0];
                        Console.WriteLine("Draft updated to include criteria in draft campaign ID {0}.",
                                          draft.draftCampaignId);
                    } catch (Exception e) {
                        throw new System.ApplicationException("Failed to create draft campaign and add " +
                                                              "criteria.", e);
                    }
                }
        }
 /// <summary>Snippet for GetCampaignCriterion</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetCampaignCriterion()
 {
     // Create client
     CampaignCriterionServiceClient campaignCriterionServiceClient = CampaignCriterionServiceClient.Create();
     // Initialize request argument(s)
     string resourceName = "customers/[CUSTOMER]/campaignCriteria/[CAMPAIGN_CRITERION]";
     // Make the request
     CampaignCriterion response = campaignCriterionServiceClient.GetCampaignCriterion(resourceName);
 }
Beispiel #4
0
 /// <summary>Snippet for GetCampaignCriterion</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetCampaignCriterionResourceNames()
 {
     // Create client
     CampaignCriterionServiceClient campaignCriterionServiceClient = CampaignCriterionServiceClient.Create();
     // Initialize request argument(s)
     CampaignCriterionName resourceName = CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]");
     // Make the request
     CampaignCriterion response = campaignCriterionServiceClient.GetCampaignCriterion(resourceName);
 }
        /// <summary>Snippet for GetCampaignCriterionAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetCampaignCriterionAsync()
        {
            // Create client
            CampaignCriterionServiceClient campaignCriterionServiceClient = await CampaignCriterionServiceClient.CreateAsync();

            // Initialize request argument(s)
            string resourceName = "customers/[CUSTOMER_ID]/campaignCriteria/[CAMPAIGN_ID]~[CRITERION_ID]";
            // Make the request
            CampaignCriterion response = await campaignCriterionServiceClient.GetCampaignCriterionAsync(resourceName);
        }
Beispiel #6
0
        /// <summary>Snippet for GetCampaignCriterionAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetCampaignCriterionResourceNamesAsync()
        {
            // Create client
            CampaignCriterionServiceClient campaignCriterionServiceClient = await CampaignCriterionServiceClient.CreateAsync();

            // Initialize request argument(s)
            CampaignCriterionName resourceName = CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER]", "[CAMPAIGN_CRITERION]");
            // Make the request
            CampaignCriterion response = await campaignCriterionServiceClient.GetCampaignCriterionAsync(resourceName);
        }
Beispiel #7
0
 /// <summary>Snippet for GetCampaignCriterion</summary>
 public void GetCampaignCriterionResourceNames()
 {
     // Snippet: GetCampaignCriterion(CampaignCriterionName, CallSettings)
     // Create client
     CampaignCriterionServiceClient campaignCriterionServiceClient = CampaignCriterionServiceClient.Create();
     // Initialize request argument(s)
     CampaignCriterionName resourceName = CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER]", "[CAMPAIGN_CRITERION]");
     // Make the request
     CampaignCriterion response = campaignCriterionServiceClient.GetCampaignCriterion(resourceName);
     // End snippet
 }
 /// <summary>Snippet for GetCampaignCriterion</summary>
 public void GetCampaignCriterion()
 {
     // Snippet: GetCampaignCriterion(string, CallSettings)
     // Create client
     CampaignCriterionServiceClient campaignCriterionServiceClient = CampaignCriterionServiceClient.Create();
     // Initialize request argument(s)
     string resourceName = "customers/[CUSTOMER_ID]/campaignCriteria/[CAMPAIGN_ID]~[CRITERION_ID]";
     // Make the request
     CampaignCriterion response = campaignCriterionServiceClient.GetCampaignCriterion(resourceName);
     // End snippet
 }
Beispiel #9
0
 /// <summary>Snippet for GetCampaignCriterion</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetCampaignCriterionRequestObject()
 {
     // Create client
     CampaignCriterionServiceClient campaignCriterionServiceClient = CampaignCriterionServiceClient.Create();
     // Initialize request argument(s)
     GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
     {
         ResourceNameAsCampaignCriterionName = CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER]", "[CAMPAIGN_CRITERION]"),
     };
     // Make the request
     CampaignCriterion response = campaignCriterionServiceClient.GetCampaignCriterion(request);
 }
Beispiel #10
0
 private string GetFieldValue(CampaignCriterion campaignCriterion, string fieldName)
 {
     return(fieldName == "Id" ? campaignCriterion.criterion.id.ToString(CultureInfo.InvariantCulture) :
            fieldName == "CriteriaType" ? campaignCriterion.criterion.type.ToString() :
            fieldName == "IsNegative" ? campaignCriterion.isNegative.ToString() :
            fieldName == "CampaignId" ? campaignCriterion.campaignId.ToString(CultureInfo.InvariantCulture) :
            fieldName == "LanguageCode" ? campaignCriterion.criterion is Language ? (campaignCriterion.criterion as Language).code : "" :
            fieldName == "LanguageName" ? campaignCriterion.criterion is Language ? (campaignCriterion.criterion as Language).name : "" :
            fieldName == "LocationName" ? campaignCriterion.criterion is Location ? (campaignCriterion.criterion as Location).locationName : "" :
            fieldName == "DisplayType" ? campaignCriterion.criterion is Location ? (campaignCriterion.criterion as Location).displayType : "" :
            "");
 }
Beispiel #11
0
        internal override void ProcessMappingsFromRowValues(RowValues values)
        {
            CampaignCriterion = new CampaignCriterion
            {
                Criterion = new ProductScope
                {
                    Type = typeof(ProductScope).Name,
                },
                Type = typeof(CampaignCriterion).Name,
            };

            values.ConvertToEntity(this, Mappings);
        }
        /// <summary>Snippet for GetCampaignCriterionAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetCampaignCriterionRequestObjectAsync()
        {
            // Create client
            CampaignCriterionServiceClient campaignCriterionServiceClient = await CampaignCriterionServiceClient.CreateAsync();

            // Initialize request argument(s)
            GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
            {
                ResourceNameAsCampaignCriterionName = CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"),
            };
            // Make the request
            CampaignCriterion response = await campaignCriterionServiceClient.GetCampaignCriterionAsync(request);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to from which targeting criteria are
        /// retrieved.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V5.GoogleAdsService);

            // Create the query.
            string query = $@"SELECT campaign.id, campaign_criterion.campaign,
                campaign_criterion.criterion_id, campaign_criterion.negative,
                campaign_criterion.keyword.text, campaign_criterion.keyword.match_type
                FROM campaign_criterion WHERE campaign.id = {campaignId}";

            try
            {
                // Issue a search request.
                PagedEnumerable <SearchGoogleAdsResponse, GoogleAdsRow> result =
                    googleAdsService.Search(customerId.ToString(), query);

                // Display the results.
                foreach (GoogleAdsRow criterionRow in result)
                {
                    CampaignCriterion criterion = criterionRow.CampaignCriterion;
                    Console.Write($"Campaign criterion with id = '{criterion.CriterionId}' " +
                                  "was retrieved:");
                    if (criterion.Negative)
                    {
                        Console.Write("Negative ");
                    }
                    switch (criterion.CriterionCase)
                    {
                    case CriterionOneofCase.Keyword:
                        Console.Write($"Keyword with text '{criterion.Keyword.Text}' ");
                        Console.WriteLine($"and match type {criterion.Keyword.MatchType}.");
                        break;

                    default:
                        Console.WriteLine("Not a Keyword!");
                        break;
                    }
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>Snippet for GetCampaignCriterionAsync</summary>
        public async Task GetCampaignCriterionResourceNamesAsync()
        {
            // Snippet: GetCampaignCriterionAsync(CampaignCriterionName, CallSettings)
            // Additional: GetCampaignCriterionAsync(CampaignCriterionName, CancellationToken)
            // Create client
            CampaignCriterionServiceClient campaignCriterionServiceClient = await CampaignCriterionServiceClient.CreateAsync();

            // Initialize request argument(s)
            CampaignCriterionName resourceName = CampaignCriterionName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]");
            // Make the request
            CampaignCriterion response = await campaignCriterionServiceClient.GetCampaignCriterionAsync(resourceName);

            // End snippet
        }
        /// <summary>Snippet for GetCampaignCriterionAsync</summary>
        public async Task GetCampaignCriterionAsync()
        {
            // Snippet: GetCampaignCriterionAsync(string, CallSettings)
            // Additional: GetCampaignCriterionAsync(string, CancellationToken)
            // Create client
            CampaignCriterionServiceClient campaignCriterionServiceClient = await CampaignCriterionServiceClient.CreateAsync();

            // Initialize request argument(s)
            string resourceName = "customers/[CUSTOMER_ID]/campaignCriteria/[CAMPAIGN_ID]~[CRITERION_ID]";
            // Make the request
            CampaignCriterion response = await campaignCriterionServiceClient.GetCampaignCriterionAsync(resourceName);

            // End snippet
        }
Beispiel #16
0
        public UpdateGeoTargetsResponse UpdateCampaignGeoTargets(string campaignId, UpdateGeoTargetsRequest updateGeoTargetsRequest)
        {
            UpdateGeoTargetsResponse updateResponse = new UpdateGeoTargetsResponse()
            {
                Success = true
            };

            Operator action = Operator.ADD;

            if (updateGeoTargetsRequest.UpdateMode == UpdateMode.Remove)
            {
                action = Operator.REMOVE;
            }

            List <KeyValuePair <string, string> > pairs = ExtractCityStatePairsFromRequets(updateGeoTargetsRequest);

            CampaignCriterionService campaignCriterionService = (CampaignCriterionService)_adwordsUser.GetService(AdWordsService.v201708.CampaignCriterionService);

            List <GeoTarget> targets = _locationNameHelper.GetTargetIdsByLocationNames(pairs);

            List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>();

            foreach (GeoTarget target in targets)
            {
                Location location = new Location()
                {
                    id = Convert.ToInt64(target.Id)
                };
                CampaignCriterionOperation operation         = new CampaignCriterionOperation();
                CampaignCriterion          campaignCriterion = new CampaignCriterion();
                campaignCriterion.campaignId            = Convert.ToInt64(campaignId);
                campaignCriterion.criterion             = location;
                campaignCriterion.CampaignCriterionType = "Location";
                operation.operand   = campaignCriterion;
                operation.@operator = action;
                operations.Add(operation);
            }

            try
            {
                CampaignCriterionReturnValue result = campaignCriterionService.mutate(operations.ToArray());
            }
            catch (Exception ex)
            {
                var exception = ex.Message;
                updateResponse.Success = false;
            }

            return(updateResponse);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the campaign whose bid should be modified.
        /// </param>
        /// <param name="bidModifier">The bid modifier.</param>
        public void Run(AdWordsUser user, long campaignId, double bidModifier)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201409.CampaignCriterionService);

            // Create mobile platform. The ID can be found in the documentation.
            // https://developers.google.com/adwords/api/docs/appendix/platforms
            Platform mobile = new Platform();

            mobile.id = 30001;

            // Create criterion with modified bid.
            CampaignCriterion criterion = new CampaignCriterion();

            criterion.campaignId  = campaignId;
            criterion.criterion   = mobile;
            criterion.bidModifier = bidModifier;

            // Create SET operation.
            CampaignCriterionOperation operation = new CampaignCriterionOperation();

            operation.@operator = Operator.SET;
            operation.operand   = criterion;

            try {
                // Update campaign criteria.
                CampaignCriterionReturnValue result = campaignCriterionService.mutate(
                    new CampaignCriterionOperation[] { operation });

                // Display campaign criteria.
                if (result.value != null)
                {
                    foreach (CampaignCriterion newCriterion in result.value)
                    {
                        Console.WriteLine("Campaign criterion with campaign id '{0}', criterion id '{1}', " +
                                          "and type '{2}' was modified with bid {3:F2}.", newCriterion.campaignId,
                                          newCriterion.criterion.id, newCriterion.criterion.type, newCriterion.bidModifier);
                    }
                }
                else
                {
                    Console.WriteLine("No campaign criteria were modified.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to set bid modifier for campaign.", ex);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign that contains the criterion.</param>
        /// <param name="criterionId">ID of the criterion for which bid modifier is updated.</param>
        /// <param name="bidModifierValue">The new value of the bid modifier to update.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId, long criterionId,
                        float?bidModifierValue)
        {
            // Get the CampaignCriterionServiceClient .
            CampaignCriterionServiceClient campaignCriterionService =
                client.GetService(Services.V10.CampaignCriterionService);

            string criterionResourceName = ResourceNames.CampaignCriteria(customerId,
                                                                          campaignId, criterionId);

            // Construct a campaign bid modifier.
            CampaignCriterion campaignCriterion = new CampaignCriterion()
            {
                ResourceName = criterionResourceName,
                BidModifier  = (bidModifierValue != null) ? bidModifierValue.Value : 1.5f,
            };

            // Construct an operation to create the campaign criterion.
            CampaignCriterionOperation op = new CampaignCriterionOperation()
            {
                Update     = campaignCriterion,
                UpdateMask = FieldMasks.AllSetFieldsOf(campaignCriterion)
            };

            // Send the operation in a mutate request.
            try
            {
                MutateCampaignCriteriaResponse response =
                    campaignCriterionService.MutateCampaignCriteria(customerId.ToString(),
                                                                    new CampaignCriterionOperation[] { op });
                foreach (MutateCampaignCriterionResult result in response.Results)
                {
                    Console.WriteLine($"Campaign criterion with resource name" +
                                      $" '{result.ResourceName}' was modified.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign for which shopping channel
        /// is set.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201406.CampaignCriterionService);

            // ProductSalesChannel is a fixed id criterion, with the possible values
            // defined here.
            // ONLINE: 200
            // LOCAL: 201
            ProductSalesChannel productSalesChannel = new ProductSalesChannel();

            productSalesChannel.id = 200;

            CampaignCriterion campaignCriterion = new CampaignCriterion();

            campaignCriterion.campaignId = campaignId;
            campaignCriterion.criterion  = productSalesChannel;

            // Create operation.
            CampaignCriterionOperation operation = new CampaignCriterionOperation();

            operation.operand   = campaignCriterion;
            operation.@operator = Operator.ADD;

            try {
                // Make the mutate request.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(
                    new CampaignCriterionOperation[] { operation });

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to set shopping product channel.", ex);
            }
        }
        public void GetCampaignCriterion2()
        {
            Mock <CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new Mock <CampaignCriterionService.CampaignCriterionServiceClient>(MockBehavior.Strict);
            GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
            {
                ResourceName = new CampaignCriteriaName("[CUSTOMER]", "[CAMPAIGN_CRITERIA]").ToString(),
            };
            CampaignCriterion expectedResponse = new CampaignCriterion
            {
                ResourceName = "resourceName2625949903",
            };

            mockGrpcClient.Setup(x => x.GetCampaignCriterion(request, It.IsAny <CallOptions>()))
            .Returns(expectedResponse);
            CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
            CampaignCriterion response            = client.GetCampaignCriterion(request);

            Assert.AreEqual(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public async Task GetCampaignCriterionAsync2()
        {
            Mock <CampaignCriterionService.CampaignCriterionServiceClient> mockGrpcClient = new Mock <CampaignCriterionService.CampaignCriterionServiceClient>(MockBehavior.Strict);
            GetCampaignCriterionRequest request = new GetCampaignCriterionRequest
            {
                ResourceName = new CampaignCriteriaName("[CUSTOMER]", "[CAMPAIGN_CRITERIA]").ToString(),
            };
            CampaignCriterion expectedResponse = new CampaignCriterion
            {
                ResourceName = "resourceName2625949903",
            };

            mockGrpcClient.Setup(x => x.GetCampaignCriterionAsync(request, It.IsAny <CallOptions>()))
            .Returns(new Grpc.Core.AsyncUnaryCall <CampaignCriterion>(Task.FromResult(expectedResponse), null, null, null, null));
            CampaignCriterionServiceClient client = new CampaignCriterionServiceClientImpl(mockGrpcClient.Object, null);
            CampaignCriterion response            = await client.GetCampaignCriterionAsync(request);

            Assert.AreEqual(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the campaign whose bid should be modified.
    /// </param>
    /// <param name="bidModifier">The bid modifier.</param>
    public void Run(AdWordsUser user, long campaignId, double bidModifier) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201509.CampaignCriterionService);

      // Create mobile platform. The ID can be found in the documentation.
      // https://developers.google.com/adwords/api/docs/appendix/platforms
      Platform mobile = new Platform();
      mobile.id = 30001;

      // Create criterion with modified bid.
      CampaignCriterion criterion = new CampaignCriterion();
      criterion.campaignId = campaignId;
      criterion.criterion = mobile;
      criterion.bidModifier = bidModifier;

      // Create SET operation.
      CampaignCriterionOperation operation = new CampaignCriterionOperation();
      operation.@operator = Operator.SET;
      operation.operand = criterion;

      try {
        // Update campaign criteria.
        CampaignCriterionReturnValue result = campaignCriterionService.mutate(
            new CampaignCriterionOperation[] {operation});

        // Display campaign criteria.
        if (result.value != null) {
          foreach (CampaignCriterion newCriterion in result.value) {
            Console.WriteLine("Campaign criterion with campaign id '{0}', criterion id '{1}', " +
                "and type '{2}' was modified with bid {3:F2}.", newCriterion.campaignId,
                newCriterion.criterion.id, newCriterion.criterion.type, newCriterion.bidModifier);
          }
        } else {
          Console.WriteLine("No campaign criteria were modified.");
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to set bid modifier for campaign.", e);
      }
    }
Beispiel #23
0
        /// <summary>
        /// Adds the campaign targeting criteria to a campaign.
        /// </summary>
        /// <param name="user">The AdWords 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.v201806
                                                          .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);
        }
Beispiel #24
0
        // [END setup_remarketing_2]

        /// <summary>
        /// Creates a campaign criterion that targets a user list with a campaign.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign on which the user list will be targeted.</param>
        /// <param name="userListResourceName">The resource name of the user list to be
        /// targeted.</param>
        /// <returns>The resource name of the newly created campaign criterion.</returns>
        // [START setup_remarketing_4]
        private string TargetAdsInCampaignToUserList(
            GoogleAdsClient client, long customerId, long campaignId, string userListResourceName)
        {
            // Get the CampaignCriterionService client.
            CampaignCriterionServiceClient campaignCriterionServiceClient =
                client.GetService(Services.V10.CampaignCriterionService);

            // Create the campaign criterion.
            CampaignCriterion campaignCriterion = new CampaignCriterion
            {
                Campaign = ResourceNames.Campaign(customerId, campaignId),
                UserList = new UserListInfo
                {
                    UserList = userListResourceName
                }
            };

            // Create the operation.
            CampaignCriterionOperation campaignCriterionOperation = new CampaignCriterionOperation
            {
                Create = campaignCriterion
            };

            // Add the campaign criterion and print the resulting criterion's resource name.
            MutateCampaignCriteriaResponse mutateCampaignCriteriaResponse =
                campaignCriterionServiceClient.MutateCampaignCriteria(customerId.ToString(),
                                                                      new[] { campaignCriterionOperation });

            string campaignCriterionResourceName =
                mutateCampaignCriteriaResponse.Results.First().ResourceName;

            Console.WriteLine("Successfully created campaign criterion with resource name " +
                              $"'{campaignCriterionResourceName}' targeting user list with resource name " +
                              $"'{userListResourceName}' with campaign with ID {campaignId}.");

            return(campaignCriterionResourceName);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        /// <param name="feedId">ID of a feed that has been configured for location
        /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
        /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
        /// If you don't have such a feed, set this value to null.</param>
        public void Run(AdWordsUser user, long campaignId, long?feedId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201506.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;

            Language language2 = new Language();

            language2.id = 1005; // Japanese
            CampaignCriterion languageCriterion2 = new CampaignCriterion();

            languageCriterion2.campaignId = campaignId;
            languageCriterion2.criterion  = language2;

            // Target Tier 3 income group near Miami, Florida.
            LocationGroups incomeLocationGroups = new LocationGroups();

            IncomeOperand incomeOperand = new IncomeOperand();

            // Tiers are numbered 1-10, and represent 10% segments of earners.
            // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
            // Tiers 6 through 10 are grouped into TIER_6_TO_10.
            incomeOperand.tier = IncomeTier.TIER_3;

            GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();

            geoTargetOperand1.locations = new long[] { 1015116 }; // Miami, FL.

            incomeLocationGroups.matchingFunction            = new Function();
            incomeLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { incomeOperand };
            incomeLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            incomeLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand1 };

            CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();

            locationGroupCriterion1.campaignId = campaignId;
            locationGroupCriterion1.criterion  = incomeLocationGroups;

            // Target places of interest near Downtown Miami, Florida.
            LocationGroups interestLocationGroups = new LocationGroups();

            PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();

            placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

            GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();

            geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL.

            interestLocationGroups.matchingFunction            = new Function();
            interestLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { placesOfInterestOperand };
            interestLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            interestLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand2 };

            CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();

            locationGroupCriterion2.campaignId = campaignId;
            locationGroupCriterion2.criterion  = interestLocationGroups;

            CampaignCriterion locationGroupCriterion3 = new CampaignCriterion();

            if (feedId.HasValue)
            {
                // Distance targeting. Area of 10 miles around targets above.
                ConstantOperand radius = new ConstantOperand();
                radius.type        = ConstantOperandConstantType.DOUBLE;
                radius.unit        = ConstantOperandUnit.MILES;
                radius.doubleValue = 10.0;
                LocationExtensionOperand distance = new LocationExtensionOperand();
                distance.radius = radius;

                LocationGroups radiusLocationGroups = new LocationGroups();
                radiusLocationGroups.matchingFunction            = new Function();
                radiusLocationGroups.matchingFunction.@operator  = FunctionOperator.IDENTITY;
                radiusLocationGroups.matchingFunction.lhsOperand =
                    new FunctionArgumentOperand[] { distance };

                // FeedID should be the ID of a feed that has been configured for location
                // targeting, meaning it has an ENABLED FeedMapping with criterionType of
                // 77. Feeds linked to a GMB account automatically have this FeedMapping.
                radiusLocationGroups.feedId = feedId.Value;

                locationGroupCriterion3.campaignId = campaignId;
                locationGroupCriterion3.criterion  = radiusLocationGroups;
            }

            // Create location criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
            // for a detailed list of country codes.
            Location location1 = new Location();

            location1.id = 2840; // USA
            CampaignCriterion locationCriterion1 = new CampaignCriterion();

            locationCriterion1.campaignId = campaignId;
            locationCriterion1.criterion  = location1;

            Location location2 = new Location();

            location2.id = 2392; // Japan
            CampaignCriterion locationCriterion2 = new CampaignCriterion();

            locationCriterion2.campaignId = campaignId;
            locationCriterion2.criterion  = location2;

            // Add a negative campaign keyword.
            NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();

            negativeCriterion.campaignId = campaignId;

            Keyword keyword = new Keyword();

            keyword.matchType = KeywordMatchType.BROAD;
            keyword.text      = "jupiter cruise";

            negativeCriterion.criterion = keyword;

            List <CampaignCriterion> criteria = new List <CampaignCriterion>(
                new CampaignCriterion[] { languageCriterion1,
                                          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion,
                                          locationGroupCriterion1, locationGroupCriterion2 });

            if (feedId.HasValue)
            {
                criteria.Add(locationGroupCriterion3);
            }

            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);
            }

            try {
                // Set the campaign targets.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", ex);
            }
        }
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                Service = new ServiceClient<ICampaignManagementService>(authorizationData);

                // Get a list of all Bing Merchant Center stores associated with your CustomerId

                IList<BMCStore> stores = await GetBMCStoresByCustomerIdAsync();
                if (stores == null)
                {
                    OutputStatusMessage(
                        String.Format("You do not have any BMC stores registered for CustomerId {0}.\n", authorizationData.CustomerId)
                    );
                    return;
                }

                #region ManageCampaign

                /* Add a new Bing Shopping campaign that will be associated with a ProductScope criterion.
                 *  - Set the CampaignType element of the Campaign to Shopping.
                 *  - Create a ShoppingSetting instance and set its Priority (0, 1, or 2), SalesCountryCode, and StoreId elements. 
                 *    Add this shopping setting to the Settings list of the Campaign.
                 */
                
                var campaign = new Campaign
                {
                    CampaignType = CampaignType.Shopping,
                    Settings = new[] { 
                        new ShoppingSetting() {
                            Priority = 0,
                            SalesCountryCode = "US",
                            StoreId = (int)stores[0].Id
                        }
                    },
                    Name = "Bing Shopping Campaign " + DateTime.UtcNow,
                    Description = "Bing Shopping Campaign Example.",
                    BudgetType = BudgetLimitType.MonthlyBudgetSpendUntilDepleted,
                    MonthlyBudget = 1000.00,
                    TimeZone = "PacificTimeUSCanadaTijuana",
                    DaylightSaving = true,
                };

                var campaignIds = await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign });
                OutputCampaignIdentifiers(campaignIds);

                /* Optionally, you can create a ProductScope criterion that will be associated with your Bing Shopping campaign. 
                 * Use the product scope criterion to include a subset of your product catalog, for example a specific brand, 
                 * category, or product type. A campaign can only be associated with one ProductScope, which contains a list 
                 * of up to 7 ProductCondition. You'll also be able to specify more specific product conditions for each ad group.
                 */

                var campaignCriterions = new CampaignCriterion[] {
                    new CampaignCriterion() {
                        CampaignId = campaignIds[0],
                        BidAdjustment = null,  // Reserved for future use
                        Criterion = new ProductScope() {
                            Conditions = new ProductCondition[] {
                                new ProductCondition {
                                    Operand = "Condition",
                                    Attribute = "New"
                                },
                                new ProductCondition {
                                    Operand = "CustomLabel0",
                                    Attribute = "MerchantDefinedCustomLabel"
                                },
                            }
                        },
                    }                        
                };

                var addCampaignCriterionsResponse = await (AddCampaignCriterionsAsync(
                    campaignCriterions,
                    CampaignCriterionType.ProductScope)
                );

                #endregion ManageCampaign

                #region ManageAdGroup

                // Specify one or more ad groups.

                var adGroup = new AdGroup
                {
                    Name = "Product Categories",
                    AdDistribution = AdDistribution.Search,
                    BiddingModel = BiddingModel.Keyword,
                    PricingModel = PricingModel.Cpc,
                    StartDate = null,
                    EndDate = new Date { Month = 12, Day = 31, Year = 2016 },
                    Language = "English"
                };

                var adGroupIds = (long[])await AddAdGroupsAsync(campaignIds[0], new[] { adGroup });
                OutputAdGroupIdentifiers(adGroupIds);

                #region BidAllProducts

                var helper = new PartitionActionHelper(adGroupIds[0]);

                var root = helper.AddUnit(
                    null,
                    new ProductCondition { Operand = "All", Attribute = null },
                    0.35,
                    false
                );

                OutputStatusMessage("Applying only the root as a Unit with a bid . . . \n");
                var applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                var adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                OutputStatusMessage("The ad group's product partition only has a tree root node: \n");
                OutputProductPartitions(adGroupCriterions);

                /*
                 * Let's update the bid of the root Unit we just added.
                 */

                BiddableAdGroupCriterion updatedRoot = new BiddableAdGroupCriterion
                {
                    Id = applyProductPartitionActionsResponse.AdGroupCriterionIds[0],
                    CriterionBid = new FixedBid
                    {
                        Bid = new Bid
                        {
                            Amount = 0.45
                        }
                    }
                };
                
                helper = new PartitionActionHelper(adGroupIds[0]);
                helper.UpdatePartition(updatedRoot);

                OutputStatusMessage("Updating the bid for the tree root node . . . \n");
                await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                OutputStatusMessage("Updated the bid for the tree root node: \n");
                OutputProductPartitions(adGroupCriterions);

                #endregion BidAllProducts

                #region InitializeTree

                /*
                 * Now we will overwrite any existing tree root, and build a product partition group tree structure in multiple steps. 
                 * You could build the entire tree in a single call since there are less than 5,000 nodes; however, 
                 * we will build it in steps to demonstrate how to use the results from ApplyProductPartitionActions to update the tree. 
                 * 
                 * For a list of validation rules, see the Bing Shopping Campaigns technical guide:
                 * https://msdn.microsoft.com/en-US/library/bing-ads-campaign-management-bing-shopping-campaigns.aspx
                 */

                helper = new PartitionActionHelper(adGroupIds[0]);

                /*
                 * Check whether a root node exists already.
                 */
                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );
                var existingRoot = GetRootNode(adGroupCriterions);
                if (existingRoot != null)
                {
                    helper.DeletePartition(existingRoot);
                }

                root = helper.AddSubdivision(
                    null, 
                    new ProductCondition { Operand = "All", Attribute = null }
                );

                /*
                 * The direct children of any node must have the same Operand. 
                 * For this example we will use CategoryL1 nodes as children of the root. 
                 * For a list of valid CategoryL1 through CategoryL5 values, see the Bing Category Taxonomy:
                 * http://advertise.bingads.microsoft.com/en-us/WWDocs/user/search/en-us/Bing_Category_Taxonomy.txt
                 */
                var animalsSubdivision = helper.AddSubdivision(
                    root,
                    new ProductCondition { Operand = "CategoryL1", Attribute = "Animals & Pet Supplies" }
                );

                /*
                 * If you use a CategoryL2 node, it must be a descendant (child or later) of a CategoryL1 node. 
                 * In other words you cannot have a CategoryL2 node as parent of a CategoryL1 node. 
                 * For this example we will a CategoryL2 node as child of the CategoryL1 Animals & Pet Supplies node. 
                 */
                var petSuppliesSubdivision = helper.AddSubdivision(
                    animalsSubdivision,
                    new ProductCondition { Operand = "CategoryL2", Attribute = "Pet Supplies" }
                );

                var brandA = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand A" },
                    0.35,
                    false
                );

                /*
                 * If you won't bid on Brand B, set the helper method's bidAmount to '0' and isNegative to true. 
                 * The helper method will create a NegativeAdGroupCriterion and apply the condition.
                 */
                var brandB = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand B" },
                    0,
                    true
                );

                var otherBrands = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = null },
                    0.35,
                    false
                );

                var otherPetSupplies = helper.AddUnit(
                    animalsSubdivision,
                    new ProductCondition { Operand = "CategoryL2", Attribute = null },
                    0.35,
                    false
                );

                var electronics = helper.AddUnit(
                    root,
                    new ProductCondition { Operand = "CategoryL1", Attribute = "Electronics" },
                    0.35,
                    false
                );

                var otherCategoryL1 = helper.AddUnit(
                    root,
                    new ProductCondition { Operand = "CategoryL1", Attribute = null },
                    0.35,
                    false
                );

                OutputStatusMessage("Applying product partitions to the ad group . . . \n");
                applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                // To retrieve product partitions after they have been applied, call GetAdGroupCriterionsByAdGroupId. 
                // The product partition with ParentCriterionId set to null is the root node.

                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                /*
                 * The product partition group tree now has 9 nodes. 
                 
                   All other (Root Node)
                    |
                    +-- Animals & Pet Supplies (CategoryL1)
                    |    |
                    |    +-- Pet Supplies (CategoryL2)
                    |    |    |
                    |    |    +-- Brand A
                    |    |    |    
                    |    |    +-- Brand B
                    |    |    |    
                    |    |    +-- All other (Brand)
                    |    |         
                    |    +-- All other (CategoryL2)
                    |        
                    +-- Electronics (CategoryL1)
                    |   
                    +-- All other (CategoryL1)

                 */

                OutputStatusMessage("The product partition group tree now has 9 nodes: \n");
                OutputProductPartitions(adGroupCriterions);

                #endregion InitializeTree

                #region UpdateTree

                /*
                 * Let's replace the Electronics (CategoryL1) node created above with an Electronics (CategoryL1) node that 
                 * has children i.e. Brand C (Brand), Brand D (Brand), and All other (Brand) as follows: 
                 
                    Electronics (CategoryL1)
                    |
                    +-- Brand C (Brand)
                    |
                    +-- Brand D (Brand)
                    |
                    +-- All other (Brand)
           
                 */

                helper = new PartitionActionHelper(adGroupIds[0]);

                /*
                 * To replace a node we must know its Id and its ParentCriterionId. In this case the parent of the node 
                 * we are replacing is All other (Root Node), and was created at Index 1 of the previous ApplyProductPartitionActions call. 
                 * The node that we are replacing is Electronics (CategoryL1), and was created at Index 8. 
                 */
                var rootId = applyProductPartitionActionsResponse.AdGroupCriterionIds[1];
                electronics.Id = applyProductPartitionActionsResponse.AdGroupCriterionIds[8];
                helper.DeletePartition(electronics);

                var parent = new BiddableAdGroupCriterion() { Id = rootId };

                var electronicsSubdivision = helper.AddSubdivision(
                    parent,
                    new ProductCondition { Operand = "CategoryL1", Attribute = "Electronics" }
                );

                var brandC = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand C" },
                    0.35,
                    false
                );

                var brandD = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand D" },
                    0.35,
                    false
                );

                var otherElectronicsBrands = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = null },
                    0.35,
                    false
                );

                OutputStatusMessage(
                    "Updating the product partition group to refine Electronics (CategoryL1) with 3 child nodes . . . \n"
                );
                applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);
                
                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                /*
                 * The product partition group tree now has 12 nodes, including the children of Electronics (CategoryL1):
                 
                   All other (Root Node)
                    |
                    +-- Animals & Pet Supplies (CategoryL1)
                    |    |
                    |    +-- Pet Supplies (CategoryL2)
                    |    |    |
                    |    |    +-- Brand A
                    |    |    |    
                    |    |    +-- Brand B
                    |    |    |    
                    |    |    +-- All other (Brand)
                    |    |         
                    |    +-- All other (CategoryL2)
                    |        
                    +-- Electronics (CategoryL1)
                    |    |
                    |    +-- Brand C (Brand)
                    |    |
                    |    +-- Brand D (Brand)
                    |    |
                    |    +-- All other (Brand)
                    |   
                    +-- All other (CategoryL1)
                 
                 */

                OutputStatusMessage(
                    "The product partition group tree now has 12 nodes, including the children of Electronics (CategoryL1): \n"
                );
                OutputProductPartitions(adGroupCriterions);

                #endregion UpdateTree

                #endregion ManageAdGroup

                #region ManageAds

                /*
                 * Create a product ad. You must add at least one ProductAd to the corresponding ad group. 
                 * A ProductAd is not used directly for delivered ad copy. Instead, the delivery engine generates 
                 * product ads from the product details that it finds in your Bing Merchant Center store's product catalog. 
                 * The primary purpose of the ProductAd object is to provide promotional text that the delivery engine 
                 * adds to the product ads that it generates. For example, if the promotional text is set to 
                 * “Free shipping on $99 purchases”, the delivery engine will set the product ad’s description to 
                 * “Free shipping on $99 purchases.”
                 */

                var ads = new Ad[] {
                    new ProductAd 
                    {
                        PromotionalText = "Free shipping on $99 purchases."
                    },
                };

                AddAdsResponse addAdsResponse = await AddAdsAsync(adGroupIds[0], ads);
                OutputAdResults(ads, addAdsResponse.AdIds, addAdsResponse.PartialErrors);

                #endregion ManageAds
                
                #region CleanUp

                /* Delete the campaign, ad group, criterion, and ad that were previously added. 
                 * You should remove this region if you want to view the added entities in the 
                 * Bing Ads web application or another tool.
                 */

                DeleteCampaignsAsync(authorizationData.AccountId, new[] { campaignIds[0] });
                OutputStatusMessage(String.Format("Deleted CampaignId {0}\n", campaignIds[0]));

                #endregion CleanUp
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException<Microsoft.BingAds.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The campaign id to add product scope.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201609.CampaignCriterionService);

            ProductScope productScope = new ProductScope();
            // This set of dimensions is for demonstration purposes only. It would be
            // extremely unlikely that you want to include so many dimensions in your
            // product scope.
            ProductBrand nexusBrand = new ProductBrand();

            nexusBrand.value = "Nexus";

            ProductCanonicalCondition newProducts = new ProductCanonicalCondition();

            newProducts.condition = ProductCanonicalConditionCondition.NEW;

            ProductCustomAttribute customAttribute = new ProductCustomAttribute();

            customAttribute.type  = ProductDimensionType.CUSTOM_ATTRIBUTE_0;
            customAttribute.value = "my attribute value";

            ProductOfferId bookOffer = new ProductOfferId();

            bookOffer.value = "book1";

            ProductType mediaProducts = new ProductType();

            mediaProducts.type  = ProductDimensionType.PRODUCT_TYPE_L1;
            mediaProducts.value = "Media";

            ProductType bookProducts = new ProductType();

            bookProducts.type  = ProductDimensionType.PRODUCT_TYPE_L2;
            bookProducts.value = "Books";

            // The value for the bidding category is a fixed ID for the
            // 'Luggage & Bags' category. You can retrieve IDs for categories from
            // the ConstantDataService. See the 'GetProductCategoryTaxonomy' example
            // for more details.
            ProductBiddingCategory luggageBiddingCategory = new ProductBiddingCategory();

            luggageBiddingCategory.type  = ProductDimensionType.BIDDING_CATEGORY_L1;
            luggageBiddingCategory.value = -5914235892932915235;

            productScope.dimensions = new ProductDimension[] { nexusBrand, newProducts, bookOffer,
                                                               mediaProducts, luggageBiddingCategory };

            CampaignCriterion campaignCriterion = new CampaignCriterion();

            campaignCriterion.campaignId = campaignId;
            campaignCriterion.criterion  = productScope;

            // Create operation.
            CampaignCriterionOperation operation = new CampaignCriterionOperation();

            operation.operand   = campaignCriterion;
            operation.@operator = Operator.ADD;

            try {
                // Make the mutate request.
                CampaignCriterionReturnValue result = campaignCriterionService.mutate(
                    new CampaignCriterionOperation[] { operation });

                Console.WriteLine("Created a ProductScope criterion with ID '{0}'",
                                  result.value[0].criterion.id);
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to set shopping product scope.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">The campaign id to add product scope.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignCriterionService.
              CampaignCriterionService campaignCriterionService =
              (CampaignCriterionService) user.GetService(
              AdWordsService.v201601.CampaignCriterionService);

              ProductScope productScope = new ProductScope();
              // This set of dimensions is for demonstration purposes only. It would be
              // extremely unlikely that you want to include so many dimensions in your
              // product scope.
              ProductBrand nexusBrand = new ProductBrand();
              nexusBrand.value = "Nexus";

              ProductCanonicalCondition newProducts = new ProductCanonicalCondition();
              newProducts.condition = ProductCanonicalConditionCondition.NEW;

              ProductCustomAttribute customAttribute = new ProductCustomAttribute();
              customAttribute.type = ProductDimensionType.CUSTOM_ATTRIBUTE_0;
              customAttribute.value = "my attribute value";

              ProductOfferId bookOffer = new ProductOfferId();
              bookOffer.value = "book1";

              ProductType mediaProducts = new ProductType();
              mediaProducts.type = ProductDimensionType.PRODUCT_TYPE_L1;
              mediaProducts.value = "Media";

              ProductType bookProducts = new ProductType();
              bookProducts.type = ProductDimensionType.PRODUCT_TYPE_L2;
              bookProducts.value = "Books";

              // The value for the bidding category is a fixed ID for the
              // 'Luggage & Bags' category. You can retrieve IDs for categories from
              // the ConstantDataService. See the 'GetProductCategoryTaxonomy' example
              // for more details.
              ProductBiddingCategory luggageBiddingCategory = new ProductBiddingCategory();
              luggageBiddingCategory.type = ProductDimensionType.BIDDING_CATEGORY_L1;
              luggageBiddingCategory.value = -5914235892932915235;

              productScope.dimensions = new ProductDimension[] {nexusBrand, newProducts, bookOffer,
              mediaProducts, luggageBiddingCategory};

              CampaignCriterion campaignCriterion = new CampaignCriterion();
              campaignCriterion.campaignId = campaignId;
              campaignCriterion.criterion = productScope;

              // Create operation.
              CampaignCriterionOperation operation = new CampaignCriterionOperation();
              operation.operand = campaignCriterion;
              operation.@operator = Operator.ADD;

              try {
            // Make the mutate request.
            CampaignCriterionReturnValue result = campaignCriterionService.mutate(
            new CampaignCriterionOperation[] { operation });

            Console.WriteLine("Created a ProductScope criterion with ID '{0}'",
              result.value[0].criterion.id);
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to set shopping product scope.", e);
              }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201502.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;

            Language language2 = new Language();

            language2.id = 1005; // Japanese
            CampaignCriterion languageCriterion2 = new CampaignCriterion();

            languageCriterion2.campaignId = campaignId;
            languageCriterion2.criterion  = language2;

            // Create location criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
            // for a detailed list of country codes.
            Location location1 = new Location();

            location1.id = 2840; // USA
            CampaignCriterion locationCriterion1 = new CampaignCriterion();

            locationCriterion1.campaignId = campaignId;
            locationCriterion1.criterion  = location1;

            Location location2 = new Location();

            location2.id = 2392; // Japan
            CampaignCriterion locationCriterion2 = new CampaignCriterion();

            locationCriterion2.campaignId = campaignId;
            locationCriterion2.criterion  = location2;

            // Add a negative campaign placement.
            NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();

            negativeCriterion.campaignId = campaignId;

            Placement placement = new Placement();

            placement.url = "http://mars.google.com";

            negativeCriterion.criterion = placement;

            CampaignCriterion[] criteria = new CampaignCriterion[] { languageCriterion1,
                                                                     languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion };

            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);
            }

            try {
                // Set the campaign targets.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">The campaign to which listing scope is added.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionServiceClient campaignCriterionService =
                client.GetService(Services.V3.CampaignCriterionService);

            // A listing scope allows you to filter the products that will be included in a given
            // campaign. You can specify multiple dimensions with conditions that must be met for
            // a product to be included in a campaign.
            // A typical ListingScope might only have a few dimensions. This example demonstrates
            // a range of different dimensions you could use.
            ListingScopeInfo listingScope = new ListingScopeInfo()
            {
                Dimensions =
                {
                    // Creates a ProductBrand dimension set to "google".
                    new ListingDimensionInfo()
                    {
                        ProductBrand = new ProductBrandInfo()
                        {
                            Value = "google"
                        }
                    },

                    // Creates a ProductCustomAttribute dimension for INDEX0 set to
                    // "top_selling_products".
                    new ListingDimensionInfo()
                    {
                        ProductCustomAttribute = new ProductCustomAttributeInfo()
                        {
                            Index = ProductCustomAttributeIndex.Index0,
                            Value = "top_selling_products"
                        }
                    },

                    // Creates a ProductType dimension for LEVEL1 set to "electronics".
                    new ListingDimensionInfo()
                    {
                        ProductType = new ProductTypeInfo()
                        {
                            Level = ProductTypeLevel.Level1,
                            Value = "electronics"
                        }
                    },

                    // Creates a ProductType dimension for LEVEL2 set to "smartphones".
                    new ListingDimensionInfo()
                    {
                        ProductType = new ProductTypeInfo()
                        {
                            Level = ProductTypeLevel.Level2,
                            Value = "smartphones"
                        }
                    },
                }
            };

            string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);

            // Creates a campaign criterion to store the listing scope.
            CampaignCriterion campaignCriterion = new CampaignCriterion()
            {
                Campaign     = campaignResourceName,
                ListingScope = listingScope
            };

            CampaignCriterionOperation operation = new CampaignCriterionOperation()
            {
                Create = campaignCriterion
            };

            try
            {
                // Calls the mutate method to add the campaign criterion.
                MutateCampaignCriteriaResponse response =
                    campaignCriterionService.MutateCampaignCriteria(
                        customerId.ToString(), new[] { operation });
                Console.WriteLine($"Added {response.Results.Count} campaign criteria:");
                foreach (MutateCampaignCriterionResult result in response.Results)
                {
                    Console.WriteLine(result.ResourceName);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to which targeting criteria
    /// are added.</param>
    public void Run(AdWordsUser user, long campaignId) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201509.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;

      Language language2 = new Language();
      language2.id = 1005; // Japanese
      CampaignCriterion languageCriterion2 = new CampaignCriterion();
      languageCriterion2.campaignId = campaignId;
      languageCriterion2.criterion = language2;

      // Create location criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
      // for a detailed list of country codes.
      Location location1 = new Location();
      location1.id = 2840; // USA
      CampaignCriterion locationCriterion1 = new CampaignCriterion();
      locationCriterion1.campaignId = campaignId;
      locationCriterion1.criterion = location1;

      Location location2 = new Location();
      location2.id = 2392; // Japan
      CampaignCriterion locationCriterion2 = new CampaignCriterion();
      locationCriterion2.campaignId = campaignId;
      locationCriterion2.criterion = location2;

      // Add a negative campaign placement.
      NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
      negativeCriterion.campaignId = campaignId;

      Placement placement = new Placement();
      placement.url = "http://mars.google.com";

      negativeCriterion.criterion = placement;

      CampaignCriterion[] criteria = new CampaignCriterion[] {languageCriterion1,
          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion};

      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);
      }

      try {
        // Set the campaign targets.
        CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

        if (retVal != null && retVal.value != null) {
          // Display campaign targets.
          foreach (CampaignCriterion criterion in retVal.value) {
            Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
          }
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to set Campaign criteria.", e);
      }
    }
        public override int GetHashCode()
        {
            int hash = 1;

            if (ResourceName.Length != 0)
            {
                hash ^= ResourceName.GetHashCode();
            }
            if (lastChangeDateTime_ != null)
            {
                hash ^= LastChangeDateTime.GetHashCode();
            }
            if (ResourceType != 0)
            {
                hash ^= ResourceType.GetHashCode();
            }
            if (campaign_ != null)
            {
                hash ^= Campaign.GetHashCode();
            }
            if (adGroup_ != null)
            {
                hash ^= AdGroup.GetHashCode();
            }
            if (ResourceStatus != 0)
            {
                hash ^= ResourceStatus.GetHashCode();
            }
            if (adGroupAd_ != null)
            {
                hash ^= AdGroupAd.GetHashCode();
            }
            if (adGroupCriterion_ != null)
            {
                hash ^= AdGroupCriterion.GetHashCode();
            }
            if (campaignCriterion_ != null)
            {
                hash ^= CampaignCriterion.GetHashCode();
            }
            if (feed_ != null)
            {
                hash ^= Feed.GetHashCode();
            }
            if (feedItem_ != null)
            {
                hash ^= FeedItem.GetHashCode();
            }
            if (adGroupFeed_ != null)
            {
                hash ^= AdGroupFeed.GetHashCode();
            }
            if (campaignFeed_ != null)
            {
                hash ^= CampaignFeed.GetHashCode();
            }
            if (adGroupBidModifier_ != null)
            {
                hash ^= AdGroupBidModifier.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        /// <summary>
        /// Outputs the CampaignCriterion that contains a Product Scope.
        /// </summary>
        protected void OutputCampaignCriterionWithProductScope(CampaignCriterion campaignCriterion)
        {
            if (campaignCriterion != null)
            {
                OutputStatusMessage(string.Format("BidAdjustment: {0}", campaignCriterion.BidAdjustment));
                OutputStatusMessage(string.Format("CampaignId: {0}", campaignCriterion.CampaignId));
                OutputStatusMessage("ForwardCompatibilityMap: ");
                if (campaignCriterion.ForwardCompatibilityMap != null)
                {
                    foreach (var pair in campaignCriterion.ForwardCompatibilityMap)
                    {
                        OutputStatusMessage(string.Format("Key: {0}", pair.Key));
                        OutputStatusMessage(string.Format("Value: {0}", pair.Value));
                    }
                }
                OutputStatusMessage(string.Format("CampaignCriterion Id: {0}", campaignCriterion.Id));
                OutputStatusMessage(string.Format("CampaignCriterion Type: {0}", campaignCriterion.Type));

                // Output the Campaign Management ProductScope Object
                OutputProductScope((ProductScope)campaignCriterion.Criterion);
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to which targeting criteria
    /// are added.</param>
    /// <param name="feedId">ID of a feed that has been configured for location
    /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
    /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
    /// If you don't have such a feed, set this value to null.</param>
    public void Run(AdWordsUser user, long campaignId, long? feedId) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201509.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;

      Language language2 = new Language();
      language2.id = 1005; // Japanese
      CampaignCriterion languageCriterion2 = new CampaignCriterion();
      languageCriterion2.campaignId = campaignId;
      languageCriterion2.criterion = language2;

      // Target Tier 3 income group near Miami, Florida.
      LocationGroups incomeLocationGroups = new LocationGroups();

      IncomeOperand incomeOperand = new IncomeOperand();
      // Tiers are numbered 1-10, and represent 10% segments of earners.
      // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
      // Tiers 6 through 10 are grouped into TIER_6_TO_10.
      incomeOperand.tier = IncomeTier.TIER_3;

      GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();
      geoTargetOperand1.locations = new long[] { 1015116 }; // Miami, FL.

      incomeLocationGroups.matchingFunction = new Function();
      incomeLocationGroups.matchingFunction.lhsOperand =
          new FunctionArgumentOperand[] { incomeOperand };
      incomeLocationGroups.matchingFunction.@operator = FunctionOperator.AND;
      incomeLocationGroups.matchingFunction.rhsOperand =
          new FunctionArgumentOperand[] { geoTargetOperand1 };

      CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();
      locationGroupCriterion1.campaignId = campaignId;
      locationGroupCriterion1.criterion = incomeLocationGroups;

      // Target places of interest near Downtown Miami, Florida.
      LocationGroups interestLocationGroups = new LocationGroups();

      PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();
      placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

      GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();
      geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL.

      interestLocationGroups.matchingFunction = new Function();
      interestLocationGroups.matchingFunction.lhsOperand =
          new FunctionArgumentOperand[] { placesOfInterestOperand };
      interestLocationGroups.matchingFunction.@operator = FunctionOperator.AND;
      interestLocationGroups.matchingFunction.rhsOperand =
          new FunctionArgumentOperand[] { geoTargetOperand2 };

      CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();
      locationGroupCriterion2.campaignId = campaignId;
      locationGroupCriterion2.criterion = interestLocationGroups;

      CampaignCriterion locationGroupCriterion3 = new CampaignCriterion();

      if (feedId.HasValue) {
        // Distance targeting. Area of 10 miles around targets above.
        ConstantOperand radius = new ConstantOperand();
        radius.type = ConstantOperandConstantType.DOUBLE;
        radius.unit = ConstantOperandUnit.MILES;
        radius.doubleValue = 10.0;
        LocationExtensionOperand distance = new LocationExtensionOperand();
        distance.radius = radius;

        LocationGroups radiusLocationGroups = new LocationGroups();
        radiusLocationGroups.matchingFunction = new Function();
        radiusLocationGroups.matchingFunction.@operator = FunctionOperator.IDENTITY;
        radiusLocationGroups.matchingFunction.lhsOperand =
            new FunctionArgumentOperand[] { distance };

        // FeedID should be the ID of a feed that has been configured for location
        // targeting, meaning it has an ENABLED FeedMapping with criterionType of
        // 77. Feeds linked to a GMB account automatically have this FeedMapping.
        radiusLocationGroups.feedId = feedId.Value;

        locationGroupCriterion3.campaignId = campaignId;
        locationGroupCriterion3.criterion = radiusLocationGroups;
      }

      // Create location criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
      // for a detailed list of country codes.
      Location location1 = new Location();
      location1.id = 2840; // USA
      CampaignCriterion locationCriterion1 = new CampaignCriterion();
      locationCriterion1.campaignId = campaignId;
      locationCriterion1.criterion = location1;

      Location location2 = new Location();
      location2.id = 2392; // Japan
      CampaignCriterion locationCriterion2 = new CampaignCriterion();
      locationCriterion2.campaignId = campaignId;
      locationCriterion2.criterion = location2;

      // Add a negative campaign keyword.
      NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
      negativeCriterion.campaignId = campaignId;

      Keyword keyword = new Keyword();
      keyword.matchType = KeywordMatchType.BROAD;
      keyword.text = "jupiter cruise";

      negativeCriterion.criterion = keyword;

      List<CampaignCriterion> criteria = new List<CampaignCriterion>(
          new CampaignCriterion[] {languageCriterion1,
          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion,
          locationGroupCriterion1, locationGroupCriterion2});

      if (feedId.HasValue) {
        criteria.Add(locationGroupCriterion3);
      }

      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);
      }

      try {
        // Set the campaign targets.
        CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

        if (retVal != null && retVal.value != null) {
          // Display campaign targets.
          foreach (CampaignCriterion criterion in retVal.value) {
            Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
          }
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to set Campaign criteria.", e);
      }
    }
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                Service = new ServiceClient <ICampaignManagementService>(authorizationData);

                // Get a list of all Bing Merchant Center stores associated with your CustomerId

                IList <BMCStore> stores = await GetBMCStoresByCustomerIdAsync();

                if (stores == null)
                {
                    OutputStatusMessage(
                        String.Format("You do not have any BMC stores registered for CustomerId {0}.\n", authorizationData.CustomerId)
                        );
                    return;
                }

                #region ManageCampaign

                /* Add a new Bing Shopping campaign that will be associated with a ProductScope criterion.
                 *  - Set the CampaignType element of the Campaign to Shopping.
                 *  - Create a ShoppingSetting instance and set its Priority (0, 1, or 2), SalesCountryCode, and StoreId elements.
                 *    Add this shopping setting to the Settings list of the Campaign.
                 */

                var campaign = new Campaign
                {
                    CampaignType = CampaignType.Shopping,
                    Settings     = new[] {
                        new ShoppingSetting()
                        {
                            Priority         = 0,
                            SalesCountryCode = "US",
                            StoreId          = (int)stores[0].Id
                        }
                    },
                    Name           = "Bing Shopping Campaign " + DateTime.UtcNow,
                    Description    = "Bing Shopping Campaign Example.",
                    BudgetType     = BudgetLimitType.MonthlyBudgetSpendUntilDepleted,
                    MonthlyBudget  = 1000.00,
                    TimeZone       = "PacificTimeUSCanadaTijuana",
                    DaylightSaving = true,
                };

                var campaignIds = await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign });

                OutputCampaignIdentifiers(campaignIds);

                /* Optionally, you can create a ProductScope criterion that will be associated with your Bing Shopping campaign.
                 * Use the product scope criterion to include a subset of your product catalog, for example a specific brand,
                 * category, or product type. A campaign can only be associated with one ProductScope, which contains a list
                 * of up to 7 ProductCondition. You'll also be able to specify more specific product conditions for each ad group.
                 */

                var campaignCriterions = new CampaignCriterion[] {
                    new CampaignCriterion()
                    {
                        CampaignId    = campaignIds[0],
                        BidAdjustment = null,  // Reserved for future use
                        Criterion     = new ProductScope()
                        {
                            Conditions = new ProductCondition[] {
                                new ProductCondition {
                                    Operand   = "Condition",
                                    Attribute = "New"
                                },
                                new ProductCondition {
                                    Operand   = "CustomLabel0",
                                    Attribute = "MerchantDefinedCustomLabel"
                                },
                            }
                        },
                    }
                };

                var addCampaignCriterionsResponse = await(AddCampaignCriterionsAsync(
                                                              campaignCriterions,
                                                              CampaignCriterionType.ProductScope)
                                                          );

                #endregion ManageCampaign

                #region ManageAdGroup

                // Specify one or more ad groups.

                var adGroup = new AdGroup
                {
                    Name           = "Product Categories",
                    AdDistribution = AdDistribution.Search,
                    BiddingModel   = BiddingModel.Keyword,
                    PricingModel   = PricingModel.Cpc,
                    StartDate      = null,
                    EndDate        = new Date {
                        Month = 12, Day = 31, Year = 2016
                    },
                    Language = "English"
                };

                var adGroupIds = (long[]) await AddAdGroupsAsync(campaignIds[0], new[] { adGroup });

                OutputAdGroupIdentifiers(adGroupIds);

                #region BidAllProducts

                var helper = new PartitionActionHelper(adGroupIds[0]);

                var root = helper.AddUnit(
                    null,
                    new ProductCondition {
                    Operand = "All", Attribute = null
                },
                    0.35,
                    false
                    );

                OutputStatusMessage("Applying only the root as a Unit with a bid . . . \n");
                var applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                var adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                    );

                OutputStatusMessage("The ad group's product partition only has a tree root node: \n");
                OutputProductPartitions(adGroupCriterions);

                /*
                 * Let's update the bid of the root Unit we just added.
                 */

                BiddableAdGroupCriterion updatedRoot = new BiddableAdGroupCriterion
                {
                    Id           = applyProductPartitionActionsResponse.AdGroupCriterionIds[0],
                    CriterionBid = new FixedBid
                    {
                        Bid = new Bid
                        {
                            Amount = 0.45
                        }
                    }
                };

                helper = new PartitionActionHelper(adGroupIds[0]);
                helper.UpdatePartition(updatedRoot);

                OutputStatusMessage("Updating the bid for the tree root node . . . \n");
                await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                    );

                OutputStatusMessage("Updated the bid for the tree root node: \n");
                OutputProductPartitions(adGroupCriterions);

                #endregion BidAllProducts

                #region InitializeTree

                /*
                 * Now we will overwrite any existing tree root, and build a product partition group tree structure in multiple steps.
                 * You could build the entire tree in a single call since there are less than 5,000 nodes; however,
                 * we will build it in steps to demonstrate how to use the results from ApplyProductPartitionActions to update the tree.
                 *
                 * For a list of validation rules, see the Bing Shopping Campaigns technical guide:
                 * https://msdn.microsoft.com/en-US/library/bing-ads-campaign-management-bing-shopping-campaigns.aspx
                 */

                helper = new PartitionActionHelper(adGroupIds[0]);

                /*
                 * Check whether a root node exists already.
                 */
                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                    );

                var existingRoot = GetRootNode(adGroupCriterions);
                if (existingRoot != null)
                {
                    helper.DeletePartition(existingRoot);
                }

                root = helper.AddSubdivision(
                    null,
                    new ProductCondition {
                    Operand = "All", Attribute = null
                }
                    );

                /*
                 * The direct children of any node must have the same Operand.
                 * For this example we will use CategoryL1 nodes as children of the root.
                 * For a list of valid CategoryL1 through CategoryL5 values, see the Bing Category Taxonomy:
                 * http://advertise.bingads.microsoft.com/en-us/WWDocs/user/search/en-us/Bing_Category_Taxonomy.txt
                 */
                var animalsSubdivision = helper.AddSubdivision(
                    root,
                    new ProductCondition {
                    Operand = "CategoryL1", Attribute = "Animals & Pet Supplies"
                }
                    );

                /*
                 * If you use a CategoryL2 node, it must be a descendant (child or later) of a CategoryL1 node.
                 * In other words you cannot have a CategoryL2 node as parent of a CategoryL1 node.
                 * For this example we will a CategoryL2 node as child of the CategoryL1 Animals & Pet Supplies node.
                 */
                var petSuppliesSubdivision = helper.AddSubdivision(
                    animalsSubdivision,
                    new ProductCondition {
                    Operand = "CategoryL2", Attribute = "Pet Supplies"
                }
                    );

                var brandA = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition {
                    Operand = "Brand", Attribute = "Brand A"
                },
                    0.35,
                    false
                    );

                /*
                 * If you won't bid on Brand B, set the helper method's bidAmount to '0' and isNegative to true.
                 * The helper method will create a NegativeAdGroupCriterion and apply the condition.
                 */
                var brandB = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition {
                    Operand = "Brand", Attribute = "Brand B"
                },
                    0,
                    true
                    );

                var otherBrands = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition {
                    Operand = "Brand", Attribute = null
                },
                    0.35,
                    false
                    );

                var otherPetSupplies = helper.AddUnit(
                    animalsSubdivision,
                    new ProductCondition {
                    Operand = "CategoryL2", Attribute = null
                },
                    0.35,
                    false
                    );

                var electronics = helper.AddUnit(
                    root,
                    new ProductCondition {
                    Operand = "CategoryL1", Attribute = "Electronics"
                },
                    0.35,
                    false
                    );

                var otherCategoryL1 = helper.AddUnit(
                    root,
                    new ProductCondition {
                    Operand = "CategoryL1", Attribute = null
                },
                    0.35,
                    false
                    );

                OutputStatusMessage("Applying product partitions to the ad group . . . \n");
                applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                // To retrieve product partitions after they have been applied, call GetAdGroupCriterionsByAdGroupId.
                // The product partition with ParentCriterionId set to null is the root node.

                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                    );

                /*
                 * The product partition group tree now has 9 nodes.
                 *
                 * All other (Root Node)
                 |
                 +-- Animals & Pet Supplies (CategoryL1)
                 |    |
                 |    +-- Pet Supplies (CategoryL2)
                 |    |    |
                 |    |    +-- Brand A
                 |    |    |
                 |    |    +-- Brand B
                 |    |    |
                 |    |    +-- All other (Brand)
                 |    |
                 |    +-- All other (CategoryL2)
                 |
                 +-- Electronics (CategoryL1)
                 |
                 +-- All other (CategoryL1)
                 |
                 */

                OutputStatusMessage("The product partition group tree now has 9 nodes: \n");
                OutputProductPartitions(adGroupCriterions);

                #endregion InitializeTree

                #region UpdateTree

                /*
                 * Let's replace the Electronics (CategoryL1) node created above with an Electronics (CategoryL1) node that
                 * has children i.e. Brand C (Brand), Brand D (Brand), and All other (Brand) as follows:
                 *
                 *  Electronics (CategoryL1)
                 |
                 +-- Brand C (Brand)
                 |
                 +-- Brand D (Brand)
                 |
                 +-- All other (Brand)
                 |
                 */

                helper = new PartitionActionHelper(adGroupIds[0]);

                /*
                 * To replace a node we must know its Id and its ParentCriterionId. In this case the parent of the node
                 * we are replacing is All other (Root Node), and was created at Index 1 of the previous ApplyProductPartitionActions call.
                 * The node that we are replacing is Electronics (CategoryL1), and was created at Index 8.
                 */
                var rootId = applyProductPartitionActionsResponse.AdGroupCriterionIds[1];
                electronics.Id = applyProductPartitionActionsResponse.AdGroupCriterionIds[8];
                helper.DeletePartition(electronics);

                var parent = new BiddableAdGroupCriterion()
                {
                    Id = rootId
                };

                var electronicsSubdivision = helper.AddSubdivision(
                    parent,
                    new ProductCondition {
                    Operand = "CategoryL1", Attribute = "Electronics"
                }
                    );

                var brandC = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition {
                    Operand = "Brand", Attribute = "Brand C"
                },
                    0.35,
                    false
                    );

                var brandD = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition {
                    Operand = "Brand", Attribute = "Brand D"
                },
                    0.35,
                    false
                    );

                var otherElectronicsBrands = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition {
                    Operand = "Brand", Attribute = null
                },
                    0.35,
                    false
                    );

                OutputStatusMessage(
                    "Updating the product partition group to refine Electronics (CategoryL1) with 3 child nodes . . . \n"
                    );
                applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                    );

                /*
                 * The product partition group tree now has 12 nodes, including the children of Electronics (CategoryL1):
                 *
                 * All other (Root Node)
                 |
                 +-- Animals & Pet Supplies (CategoryL1)
                 |    |
                 |    +-- Pet Supplies (CategoryL2)
                 |    |    |
                 |    |    +-- Brand A
                 |    |    |
                 |    |    +-- Brand B
                 |    |    |
                 |    |    +-- All other (Brand)
                 |    |
                 |    +-- All other (CategoryL2)
                 |
                 +-- Electronics (CategoryL1)
                 |    |
                 |    +-- Brand C (Brand)
                 |    |
                 |    +-- Brand D (Brand)
                 |    |
                 |    +-- All other (Brand)
                 |
                 +-- All other (CategoryL1)
                 |
                 */

                OutputStatusMessage(
                    "The product partition group tree now has 12 nodes, including the children of Electronics (CategoryL1): \n"
                    );
                OutputProductPartitions(adGroupCriterions);

                #endregion UpdateTree

                #endregion ManageAdGroup

                #region ManageAds

                /*
                 * Create a product ad. You must add at least one ProductAd to the corresponding ad group.
                 * A ProductAd is not used directly for delivered ad copy. Instead, the delivery engine generates
                 * product ads from the product details that it finds in your Bing Merchant Center store's product catalog.
                 * The primary purpose of the ProductAd object is to provide promotional text that the delivery engine
                 * adds to the product ads that it generates. For example, if the promotional text is set to
                 * “Free shipping on $99 purchases”, the delivery engine will set the product ad’s description to
                 * “Free shipping on $99 purchases.”
                 */

                var ads = new Ad[] {
                    new ProductAd
                    {
                        PromotionalText = "Free shipping on $99 purchases."
                    },
                };

                AddAdsResponse addAdsResponse = await AddAdsAsync(adGroupIds[0], ads);

                OutputAdResults(ads, addAdsResponse.AdIds, addAdsResponse.PartialErrors);

                #endregion ManageAds

                #region CleanUp

                /* Delete the campaign, ad group, criterion, and ad that were previously added.
                 * You should remove this region if you want to view the added entities in the
                 * Bing Ads web application or another tool.
                 */

                DeleteCampaignsAsync(authorizationData.AccountId, new[] { campaignIds[0] });
                OutputStatusMessage(String.Format("Deleted CampaignId {0}\n", campaignIds[0]));

                #endregion CleanUp
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException <Microsoft.BingAds.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException <Microsoft.BingAds.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
Beispiel #36
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignId">ID of the campaign to which targeting criteria are added.
        /// </param>
        /// <param name="keywordText">the keyword text for which to add a criterion.</param>
        /// <param name="locationId">the locationId for which to add a criterion.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId,
                        string keywordText, long locationId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionServiceClient campaignCriterionService =
                client.GetService(Services.V1.CampaignCriterionService);

            // Set the Campaign Resource Name
            string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);

            // Add a campaign level negative keyword from keywordText.
            CampaignCriterion keywordCriterion = buildNegativeKeywordCriterion(keywordText,
                                                                               campaignResourceName);

            // Creates a location constant (provided by GeoTargetConstantService) as a campaign
            // targeting criterion. Please refer to GetGeoTargetConstantsByName.cs for retrieval
            // of location constants.
            CampaignCriterion locationCriterion = buildLocationCriterion(locationId,
                                                                         campaignResourceName);

            // Add a proximity criterion
            CampaignCriterion proximityCriterion = buildProximityCriterion(campaignResourceName);

            // Create the operations.
            CampaignCriterionOperation negativeCriterionOperation =
                new CampaignCriterionOperation()
            {
                Create = keywordCriterion
            };

            CampaignCriterionOperation locationCriterionOperation =
                new CampaignCriterionOperation()
            {
                Create = locationCriterion
            };

            CampaignCriterionOperation proximityCriterionOperation =
                new CampaignCriterionOperation()
            {
                Create = proximityCriterion
            };

            CampaignCriterionOperation[] operations = new CampaignCriterionOperation[] {
                negativeCriterionOperation,
                locationCriterionOperation,
                proximityCriterionOperation
            };

            try
            {
                // Create the campaign criterion.
                MutateCampaignCriteriaResponse response =
                    campaignCriterionService.MutateCampaignCriteria(customerId.ToString(),
                                                                    operations);

                // Display the results.
                foreach (MutateCampaignCriterionResult criterionResult in response.Results)
                {
                    Console.WriteLine($"New campaign criterion with resource name = " +
                                      $"'{criterionResult.ResourceName}' was added to campaign " +
                                      "ID {campaignId}.");
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }
        internal override void ProcessMappingsFromRowValues(RowValues values)
        {
            CampaignCriterion = new CampaignCriterion
            {
                Criterion = new ProductScope
                {
                    Type = typeof(ProductScope).Name,
                },
                Type = typeof(CampaignCriterion).Name,
            };

            values.ConvertToEntity(this, Mappings);
        }
Beispiel #38
0
        /// <summary>
        /// Sets campaign targeting criteria for a given campaign. Both location and language
        /// targeting are illustrated.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignResourceName">The resource name of the campaign to apply
        /// targeting to.</param>
        private void SetCampaignTargetingCriteria(GoogleAdsClient client, long customerId,
                                                  string campaignResourceName)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionServiceClient campaignCriterionService = client.GetService(
                Services.V4.CampaignCriterionService);

            List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>();

            // Creates the location campaign criteria.
            // Besides using location_id, you can also search by location names from
            // GeoTargetConstantService.suggestGeoTargetConstants() and directly
            // apply GeoTargetConstant.resource_name here. An example can be found
            // in GetGeoTargetConstantByNames.cs.
            int[] locationIds = new int[]
            {
                21137, // California
                2484   // Mexico
            };

            foreach (int locationId in locationIds)
            {
                // Creates a campaign criterion.
                CampaignCriterion campaignCriterion = new CampaignCriterion()
                {
                    Campaign = campaignResourceName,
                    Type     = CriterionType.Location,
                    Location = new LocationInfo()
                    {
                        GeoTargetConstant = ResourceNames.GeoTargetConstant(locationId)
                    }
                };

                // Creates a campaign criterion operation.
                CampaignCriterionOperation operation = new CampaignCriterionOperation()
                {
                    Create = campaignCriterion
                };

                operations.Add(operation);
            }

            // Creates the language campaign criteria.
            int[] languageIds = new int[]
            {
                1000, // English
                1003  // Spanish
            };

            foreach (int languageId in languageIds)
            {
                // Creates a campaign criterion.
                CampaignCriterion campaignCriterion = new CampaignCriterion()
                {
                    Campaign = campaignResourceName,
                    Type     = CriterionType.Language,
                    Language = new LanguageInfo()
                    {
                        LanguageConstant = ResourceNames.LanguageConstant(languageId)
                    }
                };

                // Creates a campaign criterion operation.
                CampaignCriterionOperation operation = new CampaignCriterionOperation()
                {
                    Create = campaignCriterion
                };

                operations.Add(operation);
            }

            // Submits the criteria operations and prints their information.
            MutateCampaignCriteriaResponse response =
                campaignCriterionService.MutateCampaignCriteria(customerId.ToString(), operations);

            Console.WriteLine($"Created {response.Results.Count} campaign criteria with " +
                              $"resource names:");

            foreach (MutateCampaignCriterionResult result in response.Results)
            {
                Console.WriteLine(result.ResourceName);
            }
        }