Exemplo n.º 1
0
        /// <summary>
        /// Creates an explicit budget to be used only to create the Campaign.
        /// </summary>
        /// <param name="budgetService">The budget service.</param>
        /// <param name="name">The budget name.</param>
        /// <param name="amount">The budget amount.</param>
        /// <returns>The budget object.</returns>
        private Budget CreateSharedBudget(BudgetService budgetService, String name, long amount)
        {
            // Create a shared budget
            Budget budget = new Budget();

            budget.name               = name;
            budget.amount             = new Money();
            budget.amount.microAmount = amount;
            budget.deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD;
            budget.isExplicitlyShared = true;

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

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

            // Make the mutate request.
            return(budgetService.mutate(new BudgetOperation[] { operation }).value[0]);
        }
Exemplo n.º 2
0
    public long CreateBudget(AdWordsUser user) {
      BudgetService budgetService =
          (BudgetService) user.GetService(AdWordsService.v201509.BudgetService);

      // Create the campaign budget.
      Budget budget = new Budget();
      budget.name = "Interplanetary Cruise Budget #" + DateTime.Now.ToString(
          "yyyy-M-d H:m:s.ffffff");
      budget.period = BudgetBudgetPeriod.DAILY;
      budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
      budget.amount = new Money();
      budget.amount.microAmount = 500000;

      BudgetOperation budgetOperation = new BudgetOperation();
      budgetOperation.@operator = Operator.ADD;
      budgetOperation.operand = budget;

      BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[] { budgetOperation });
      return budgetRetval.value[0].budgetId;
    }
        /// <summary>
        /// Builds an operation for creating a budget.
        /// </summary>
        /// <returns>The operation for creating a budget.</returns>
        private static BudgetOperation BuildBudgetOperation()
        {
            Budget budget = new Budget()
            {
                budgetId = NextId(),
                name     = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
                amount   = new Money()
                {
                    microAmount = 50000000L,
                },
                deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
            };

            BudgetOperation budgetOperation = new BudgetOperation()
            {
                operand   = budget,
                @operator = Operator.ADD
            };

            return(budgetOperation);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates the budget.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <returns>The newly created budget.</returns>
        private static Budget CreateBudget(AdWordsUser user)
        {
            using (BudgetService budgetService =
                       (BudgetService)user.GetService(AdWordsService.v201802.BudgetService))
            {
                // Create the campaign budget.
                Budget budget = new Budget
                {
                    name           = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
                    deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
                    amount         = new Money
                    {
                        microAmount = 500000
                    }
                };

                BudgetOperation budgetOperation = new BudgetOperation
                {
                    @operator = Operator.ADD,
                    operand   = budget
                };

                try
                {
                    BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[]
                    {
                        budgetOperation
                    });
                    Budget newBudget = budgetRetval.value[0];
                    Console.WriteLine("Budget with ID = '{0}' and name = '{1}' was created.",
                                      newBudget.budgetId, newBudget.name);
                    budgetService.Close();
                    return(newBudget);
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to add budget.", e);
                }
            }
        }
        /// <summary>
        /// Creates the budget for the campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <returns>The budget.</returns>
        private Budget CreateBudget(AdWordsUser user)
        {
            // Get the BudgetService.
            using (BudgetService budgetService =
                       (BudgetService)user.GetService(AdWordsService.v201802.BudgetService))
            {
                // Create the campaign budget.
                Budget budget = new Budget
                {
                    name =
                        "Interplanetary Cruise App Budget #" + ExampleUtilities.GetRandomString(),
                    deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
                    amount         = new Money
                    {
                        microAmount = 5000000
                    },

                    // Universal app campaigns don't support shared budgets.
                    isExplicitlyShared = false
                };

                BudgetOperation budgetOperation = new BudgetOperation
                {
                    @operator = Operator.ADD,
                    operand   = budget
                };

                BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[]
                {
                    budgetOperation
                });
                Budget newBudget = budgetRetval.value[0];

                Console.WriteLine("Budget with ID = '{0}' and name = '{1}' was created.",
                                  newBudget.budgetId, newBudget.name);
                return(newBudget);
            }
        }
Exemplo n.º 6
0
        public long CreateBudget(AdWordsUser user)
        {
            BudgetService budgetService =
                (BudgetService)user.GetService(AdWordsService.v201406.BudgetService);

            // Create the campaign budget.
            Budget budget = new Budget();

            budget.name               = "Interplanetary Cruise Budget #" + DateTime.Now.ToString("yyyy-M-d H:m:s.ffffff");
            budget.period             = BudgetBudgetPeriod.DAILY;
            budget.deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD;
            budget.amount             = new Money();
            budget.amount.microAmount = 500000;

            BudgetOperation budgetOperation = new BudgetOperation();

            budgetOperation.@operator = Operator.ADD;
            budgetOperation.operand   = budget;

            BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[] { budgetOperation });

            return(budgetRetval.value[0].budgetId);
        }
        /// <summary>
        /// Creates the budget.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <returns>The new budget.</returns>
        public Budget CreateBudget(AdWordsUser user)
        {
            using (BudgetService budgetService = (BudgetService)user.GetService(
                       AdWordsService.v201708.BudgetService)) {
                Budget budget = new Budget()
                {
                    name   = "Budget #" + ExampleUtilities.GetRandomString(),
                    amount = new Money()
                    {
                        microAmount = 50000000L
                    },
                    deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD
                };

                BudgetOperation budgetOperation = new BudgetOperation()
                {
                    @operator = Operator.ADD,
                    operand   = budget
                };

                return(budgetService.mutate(new BudgetOperation[] { budgetOperation }).value[0]);
            }
        }
        /// <summary>
        /// Creates the budget for the campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <returns>The budget instance.</returns>
        private static Budget CreateBudget(AdWordsUser user)
        {
            using (BudgetService budgetService =
                       (BudgetService)user.GetService(AdWordsService.v201806.BudgetService)) {
                // Create the campaign budget.
                Budget budget = new Budget();
                budget.name               = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
                budget.deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD;
                budget.amount             = new Money();
                budget.amount.microAmount = 500000;

                BudgetOperation budgetOperation = new BudgetOperation();
                budgetOperation.@operator = Operator.ADD;
                budgetOperation.operand   = budget;

                try {
                    BudgetReturnValue budgetRetval = budgetService.mutate(
                        new BudgetOperation[] { budgetOperation });
                    return(budgetRetval.value[0]);
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to add shared budget.", e);
                }
            }
        }
        /// <summary>
        /// Creates an explicit budget to be used only to create the Campaign.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="name">The budget name.</param>
        /// <param name="amount">The budget amount.</param>
        /// <returns>The budget object.</returns>
        private Budget CreateSharedBudget(AdWordsUser user, string name, long amount)
        {
            using (BudgetService budgetService = (BudgetService)user.GetService(
                       AdWordsService.v201802.BudgetService)) {
                // Create a shared budget
                Budget budget = new Budget {
                    name   = name,
                    amount = new Money {
                        microAmount = amount
                    },
                    deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD,
                    isExplicitlyShared = true
                };

                // Create operation.
                BudgetOperation operation = new BudgetOperation {
                    operand   = budget,
                    @operator = Operator.ADD
                };

                // Make the mutate request.
                return(budgetService.mutate(new BudgetOperation[] { operation }).value[0]);
            }
        }
        /// <summary>
        /// Builds an operation for creating a budget.
        /// </summary>
        /// <returns>The operation for creating a budget.</returns>
        private static BudgetOperation BuildBudgetOperation()
        {
            Budget budget = new Budget() {
            budgetId = NextId(),
            name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
            amount = new Money() {
              microAmount = 50000000L,
            },
            deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD,
            period = BudgetBudgetPeriod.DAILY
              };

              BudgetOperation budgetOperation = new BudgetOperation() {
            operand = budget,
            @operator = Operator.ADD
              };
              return budgetOperation;
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (BatchJobService batchJobService =
                       (BatchJobService)user.GetService(AdWordsService.v201806.BatchJobService))
            {
                try
                {
                    // Create a BatchJob.
                    BatchJobOperation addOp = new BatchJobOperation()
                    {
                        @operator = Operator.ADD,
                        operand   = new BatchJob()
                    };

                    BatchJob batchJob = batchJobService.mutate(new BatchJobOperation[]
                    {
                        addOp
                    }).value[0];

                    // Get the upload URL from the new job.
                    string uploadUrl = batchJob.uploadUrl.url;

                    Console.WriteLine(
                        "Created BatchJob with ID {0}, status '{1}' and upload URL {2}.",
                        batchJob.id, batchJob.status, batchJob.uploadUrl.url);

                    BatchJobUtilities batchJobUploadHelper = new BatchJobUtilities(user);

                    // Create a resumable Upload URL to upload the operations.
                    string resumableUploadUrl =
                        batchJobUploadHelper.GetResumableUploadUrl(uploadUrl);

                    BatchUploadProgress uploadProgress =
                        batchJobUploadHelper.BeginStreamUpload(resumableUploadUrl);

                    // Create and add an operation to create a new budget.
                    BudgetOperation budgetOperation = BuildBudgetOperation();

                    uploadProgress = batchJobUploadHelper.StreamUpload(uploadProgress,
                                                                       new List <Operation>()
                    {
                        budgetOperation
                    });

                    // Create and add operations to create new campaigns.
                    List <Operation> campaignOperations = new List <Operation>();
                    campaignOperations.AddRange(
                        BuildCampaignOperations(budgetOperation.operand.budgetId));

                    uploadProgress =
                        batchJobUploadHelper.StreamUpload(uploadProgress, campaignOperations);

                    // Create and add operations to create new ad groups.
                    List <Operation> adGroupOperations = new List <Operation>();
                    foreach (CampaignOperation campaignOperation in campaignOperations)
                    {
                        adGroupOperations.AddRange(
                            BuildAdGroupOperations(campaignOperation.operand.id));
                    }

                    uploadProgress =
                        batchJobUploadHelper.StreamUpload(uploadProgress, adGroupOperations);

                    // Create and add operations to create new ad group ads (expanded text ads).
                    List <Operation> adOperations = new List <Operation>();
                    foreach (AdGroupOperation adGroupOperation in adGroupOperations)
                    {
                        adOperations.AddRange(
                            BuildAdGroupAdOperations(adGroupOperation.operand.id));
                    }

                    uploadProgress =
                        batchJobUploadHelper.StreamUpload(uploadProgress, adOperations);

                    // Create and add operations to create new ad group criteria (keywords).
                    List <Operation> keywordOperations = new List <Operation>();
                    foreach (AdGroupOperation adGroupOperation in adGroupOperations)
                    {
                        keywordOperations.AddRange(
                            BuildAdGroupCriterionOperations(adGroupOperation.operand.id));
                    }

                    uploadProgress =
                        batchJobUploadHelper.StreamUpload(uploadProgress, keywordOperations);

                    // Mark the upload as complete.
                    batchJobUploadHelper.EndStreamUpload(uploadProgress);

                    bool isCompleted = batchJobUploadHelper.WaitForPendingJob(batchJob.id,
                                                                              TIME_TO_WAIT_FOR_COMPLETION,
                                                                              delegate(BatchJob waitBatchJob, long timeElapsed)
                    {
                        Console.WriteLine("[{0} seconds]: Batch job ID {1} has status '{2}'.",
                                          timeElapsed / 1000, waitBatchJob.id, waitBatchJob.status);
                        batchJob = waitBatchJob;
                        return(false);
                    });

                    if (!isCompleted)
                    {
                        throw new TimeoutException(
                                  "Job is still in pending state after waiting for " +
                                  TIME_TO_WAIT_FOR_COMPLETION + " seconds.");
                    }

                    if (batchJob.processingErrors != null)
                    {
                        foreach (BatchJobProcessingError processingError in batchJob
                                 .processingErrors)
                        {
                            Console.WriteLine("  Processing error: {0}, {1}, {2}, {3}, {4}",
                                              processingError.ApiErrorType, processingError.trigger,
                                              processingError.errorString, processingError.fieldPath,
                                              processingError.reason);
                        }
                    }

                    if (batchJob.downloadUrl != null && batchJob.downloadUrl.url != null)
                    {
                        BatchJobMutateResponse mutateResponse =
                            batchJobUploadHelper.Download(batchJob.downloadUrl.url);
                        Console.WriteLine("Downloaded results from {0}.", batchJob.downloadUrl.url);
                        foreach (MutateResult mutateResult in mutateResponse.rval)
                        {
                            string outcome = mutateResult.errorList == null ? "SUCCESS" : "FAILURE";
                            Console.WriteLine("  Operation [{0}] - {1}", mutateResult.index,
                                              outcome);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException(
                              "Failed to add campaigns using batch job.", e);
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the BudgetService.
              BudgetService budgetService =
              (BudgetService) user.GetService(AdWordsService.v201601.BudgetService);

              // Get the CampaignService.
              CampaignService campaignService =
              (CampaignService) user.GetService(AdWordsService.v201601.CampaignService);

              // Create the campaign budget.
              Budget budget = new Budget();
              budget.name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
              budget.period = BudgetBudgetPeriod.DAILY;
              budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
              budget.amount = new Money();
              budget.amount.microAmount = 500000;

              BudgetOperation budgetOperation = new BudgetOperation();
              budgetOperation.@operator = Operator.ADD;
              budgetOperation.operand = budget;

              try {
            BudgetReturnValue budgetRetval = budgetService.mutate(
            new BudgetOperation[] { budgetOperation });
            budget = budgetRetval.value[0];
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add shared budget.", e);
              }

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

              for (int i = 0; i < NUM_ITEMS; i++) {
            // Create the campaign.
            Campaign campaign = new Campaign();
            campaign.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
            campaign.status = CampaignStatus.PAUSED;
            campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

            BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
            biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;
            campaign.biddingStrategyConfiguration = biddingConfig;

            campaign.budget = new Budget();
            campaign.budget.budgetId = budget.budgetId;

            // Set the campaign network options.
            campaign.networkSetting = new NetworkSetting();
            campaign.networkSetting.targetGoogleSearch = true;
            campaign.networkSetting.targetSearchNetwork = true;
            campaign.networkSetting.targetContentNetwork = false;
            campaign.networkSetting.targetPartnerSearchNetwork = false;

            // Set the campaign settings for Advanced location options.
            GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();
            geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE;
            geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE;

            campaign.settings = new Setting[] { geoSetting };

            // Optional: Set the start date.
            campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

            // Optional: Set the end date.
            campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd");

            // Optional: Set the campaign ad serving optimization status.
            campaign.adServingOptimizationStatus = AdServingOptimizationStatus.ROTATE;

            // Optional: Set the frequency cap.
            FrequencyCap frequencyCap = new FrequencyCap();
            frequencyCap.impressions = 5;
            frequencyCap.level = Level.ADGROUP;
            frequencyCap.timeUnit = TimeUnit.DAY;
            campaign.frequencyCap = frequencyCap;

            // Create the operation.
            CampaignOperation operation = new CampaignOperation();
            operation.@operator = Operator.ADD;
            operation.operand = campaign;

            operations.Add(operation);
              }

              try {
            // Add the campaign.
            CampaignReturnValue retVal = campaignService.mutate(operations.ToArray());

            // Display the results.
            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              foreach (Campaign newCampaign in retVal.value) {
            Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
                newCampaign.name, newCampaign.id);
              }
            } else {
              Console.WriteLine("No campaigns were added.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to add campaigns.", e);
              }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the BudgetService.
            BudgetService budgetService =
                (BudgetService)user.GetService(AdWordsService.v201605.BudgetService);

            // Get the CampaignService.
            CampaignService campaignService =
                (CampaignService)user.GetService(AdWordsService.v201605.CampaignService);

            // Create the campaign budget.
            Budget budget = new Budget();

            budget.name               = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
            budget.deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD;
            budget.amount             = new Money();
            budget.amount.microAmount = 500000;

            BudgetOperation budgetOperation = new BudgetOperation();

            budgetOperation.@operator = Operator.ADD;
            budgetOperation.operand   = budget;

            try {
                BudgetReturnValue budgetRetval = budgetService.mutate(
                    new BudgetOperation[] { budgetOperation });
                budget = budgetRetval.value[0];
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add shared budget.", e);
            }

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

            for (int i = 0; i < NUM_ITEMS; i++)
            {
                // Create the campaign.
                Campaign campaign = new Campaign();
                campaign.name   = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
                campaign.status = CampaignStatus.PAUSED;
                campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

                BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
                biddingConfig.biddingStrategyType     = BiddingStrategyType.MANUAL_CPC;
                campaign.biddingStrategyConfiguration = biddingConfig;

                campaign.budget          = new Budget();
                campaign.budget.budgetId = budget.budgetId;

                // Set the campaign network options.
                campaign.networkSetting = new NetworkSetting();
                campaign.networkSetting.targetGoogleSearch         = true;
                campaign.networkSetting.targetSearchNetwork        = true;
                campaign.networkSetting.targetContentNetwork       = false;
                campaign.networkSetting.targetPartnerSearchNetwork = false;

                // Set the campaign settings for Advanced location options.
                GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();
                geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE;
                geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE;

                campaign.settings = new Setting[] { geoSetting };

                // Optional: Set the start date.
                campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

                // Optional: Set the end date.
                campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd");

                // Optional: Set the campaign ad serving optimization status.
                campaign.adServingOptimizationStatus = AdServingOptimizationStatus.ROTATE;

                // Optional: Set the frequency cap.
                FrequencyCap frequencyCap = new FrequencyCap();
                frequencyCap.impressions = 5;
                frequencyCap.level       = Level.ADGROUP;
                frequencyCap.timeUnit    = TimeUnit.DAY;
                campaign.frequencyCap    = frequencyCap;

                // Create the operation.
                CampaignOperation operation = new CampaignOperation();
                operation.@operator = Operator.ADD;
                operation.operand   = campaign;

                operations.Add(operation);
            }

            try {
                // Add the campaign.
                CampaignReturnValue retVal = campaignService.mutate(operations.ToArray());

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    foreach (Campaign newCampaign in retVal.value)
                    {
                        Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
                                          newCampaign.name, newCampaign.id);
                    }
                }
                else
                {
                    Console.WriteLine("No campaigns were added.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add campaigns.", e);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the BatchJobService.
            BatchJobService batchJobService = (BatchJobService)user.GetService(
                AdWordsService.v201509.BatchJobService);

            try {
                // Create a BatchJob.
                BatchJobOperation addOp = new BatchJobOperation()
                {
                    @operator = Operator.ADD,
                    operand   = new BatchJob()
                };

                BatchJob batchJob = batchJobService.mutate(new BatchJobOperation[] { addOp }).value[0];

                // Get the upload URL from the new job.
                string uploadUrl = batchJob.uploadUrl.url;

                Console.WriteLine("Created BatchJob with ID {0}, status '{1}' and upload URL {2}.",
                                  batchJob.id, batchJob.status, batchJob.uploadUrl.url);

                // Create the mutate request that will be sent to the upload URL.
                List <Operation> operations = new List <Operation>();

                // Create and add an operation to create a new budget.
                BudgetOperation budgetOperation = BuildBudgetOperation();
                operations.Add(budgetOperation);

                // Create and add operations to create new campaigns.
                List <CampaignOperation> campaignOperations =
                    BuildCampaignOperations(budgetOperation.operand.budgetId);
                operations.AddRange(campaignOperations);

                // Create and add operations to create new ad groups.
                List <AdGroupOperation> adGroupOperations = new List <AdGroupOperation>();
                foreach (CampaignOperation campaignOperation in campaignOperations)
                {
                    adGroupOperations.AddRange(BuildAdGroupOperations(campaignOperation.operand.id));
                }
                operations.AddRange(adGroupOperations);

                // Create and add operations to create new ad group criteria (keywords).
                foreach (AdGroupOperation adGroupOperation in adGroupOperations)
                {
                    operations.AddRange(BuildAdGroupAdOperations(adGroupOperation.operand.id));
                }

                // Create and add operations to create new ad group ads (text ads).
                foreach (AdGroupOperation adGroupOperation in adGroupOperations)
                {
                    operations.AddRange(BuildAdGroupCriterionOperations(adGroupOperation.operand.id));
                }

                BatchJobUtilities batchJobUploadHelper = new BatchJobUtilities(user);

                // Use the BatchJobUploadHelper to upload all operations.
                batchJobUploadHelper.Upload(uploadUrl, operations.ToArray());

                long pollAttempts = 0;
                bool isPending    = true;
                do
                {
                    int sleepMillis = (int)Math.Pow(2, pollAttempts) *
                                      POLL_INTERVAL_SECONDS_BASE * 1000;
                    Console.WriteLine("Sleeping {0} millis...", sleepMillis);
                    Thread.Sleep(sleepMillis);

                    Selector selector = new Selector()
                    {
                        fields = new string[] { BatchJob.Fields.Id, BatchJob.Fields.Status,
                                                BatchJob.Fields.DownloadUrl, BatchJob.Fields.ProcessingErrors,
                                                BatchJob.Fields.ProgressStats },
                        predicates = new Predicate[] {
                            Predicate.Equals(BatchJob.Fields.Id, batchJob.id)
                        }
                    };
                    batchJob = batchJobService.get(selector).entries[0];

                    Console.WriteLine("Batch job ID {0} has status '{1}'.", batchJob.id, batchJob.status);
                    isPending = PENDING_STATUSES.Contains(batchJob.status);
                } while (isPending && ++pollAttempts <= MAX_RETRIES);

                if (isPending)
                {
                    throw new TimeoutException("Job is still in pending state after polling " +
                                               MAX_RETRIES + " times.");
                }

                if (batchJob.processingErrors != null)
                {
                    foreach (BatchJobProcessingError processingError in batchJob.processingErrors)
                    {
                        Console.WriteLine("  Processing error: {0}, {1}, {2}, {3}, {4}",
                                          processingError.ApiErrorType, processingError.trigger,
                                          processingError.errorString, processingError.fieldPath,
                                          processingError.reason);
                    }
                }

                if (batchJob.downloadUrl != null && batchJob.downloadUrl.url != null)
                {
                    BatchJobMutateResponse mutateResponse = batchJobUploadHelper.Download(
                        batchJob.downloadUrl.url);
                    Console.WriteLine("Downloaded results from {0}.", batchJob.downloadUrl.url);
                    foreach (MutateResult mutateResult in mutateResponse.rval)
                    {
                        String outcome = mutateResult.errorList == null ? "SUCCESS" : "FAILURE";
                        Console.WriteLine("  Operation [{0}] - {1}", mutateResult.index, outcome);
                    }
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to add campaigns using batch job.", e);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the BudgetService.
            BudgetService budgetService =
                (BudgetService)user.GetService(AdWordsService.v201402.BudgetService);

            // Get the VideoCampaignService.
            VideoCampaignService videoCampaignService =
                (VideoCampaignService)user.GetService(AdWordsService.v201402.VideoCampaignService);

            // Create the campaign budget.
            Budget budget = new Budget();

            budget.name               = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
            budget.period             = BudgetBudgetPeriod.DAILY;
            budget.deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD;
            budget.amount             = new Money();
            budget.amount.microAmount = 500000;

            BudgetOperation budgetOperation = new BudgetOperation();

            budgetOperation.@operator = Operator.ADD;
            budgetOperation.operand   = budget;

            try {
                BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[] { budgetOperation });
                budget = budgetRetval.value[0];
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to add shared budget.", ex);
            }

            // Create video campaign.
            VideoCampaign videoCampaign = new VideoCampaign();

            videoCampaign.name     = ("Interplanetary Cruise #" + ExampleUtilities.GetRandomString());
            videoCampaign.status   = VideoCampaignStatus.PAUSED;
            videoCampaign.budgetId = budget.budgetId;

            // You can optionally provide these field(s). The dates will be
            // interpreted using the account's timezone.
            videoCampaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

            try {
                // Create operations.
                VideoCampaignOperation operation = new VideoCampaignOperation();
                operation.operand   = videoCampaign;
                operation.@operator = Operator.ADD;

                VideoCampaignOperation[] operations = new VideoCampaignOperation[] { operation };

                // Add video campaigns.
                VideoCampaignReturnValue retval = videoCampaignService.mutate(operations);

                // Display video campaigns.
                if (retval != null && retval.value != null && retval.value.Length > 0)
                {
                    VideoCampaign newVideoCampaign = retval.value[0];
                    Console.WriteLine("Campaign with name '{0}' and id = {1} was added.",
                                      newVideoCampaign.name, newVideoCampaign.id);
                }
                else
                {
                    Console.WriteLine("No video campaigns were added.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to add video campaign.", ex);
            }
        }
    /// <summary>
    /// Creates an explicit budget to be used only to create the Campaign.
    /// </summary>
    /// <param name="budgetService">The budget service.</param>
    /// <param name="name">The budget name.</param>
    /// <param name="amount">The budget amount.</param>
    /// <returns>The budget object.</returns>
    private Budget CreateSharedBudget(BudgetService budgetService, String name, long amount) {
      // Create a shared budget
      Budget budget = new Budget();
      budget.name = name;
      budget.period = BudgetBudgetPeriod.DAILY;
      budget.amount = new Money();
      budget.amount.microAmount = amount;
      budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
      budget.isExplicitlyShared = true;

      // Create operation.
      BudgetOperation operation = new BudgetOperation();
      operation.operand = budget;
      operation.@operator = Operator.ADD;

      // Make the mutate request.
      return budgetService.mutate(new BudgetOperation[] {operation}).value[0];
    }
Exemplo n.º 17
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            // Get the CampaignService.
            BudgetService budgetService =
                (BudgetService)user.GetService(AdWordsService.v201402.BudgetService);

            // Get the CampaignService.
            CampaignService campaignService =
                (CampaignService)user.GetService(AdWordsService.v201402.CampaignService);

            // Create the campaign budget.
            Budget budget = new Budget();

            budget.name               = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
            budget.period             = BudgetBudgetPeriod.DAILY;
            budget.deliveryMethod     = BudgetBudgetDeliveryMethod.STANDARD;
            budget.amount             = new Money();
            budget.amount.microAmount = 500000;

            BudgetOperation budgetOperation = new BudgetOperation();

            budgetOperation.@operator = Operator.ADD;
            budgetOperation.operand   = budget;

            try {
                BudgetReturnValue budgetRetval = budgetService.mutate(new BudgetOperation[] { budgetOperation });
                budget = budgetRetval.value[0];
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to add shared budget.", ex);
            }

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

            for (int i = 0; i < NUM_ITEMS; i++)
            {
                // Create the campaign.
                Campaign campaign = new Campaign();
                campaign.name   = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
                campaign.status = CampaignStatus.PAUSED;
                campaign.advertisingChannelType = AdvertisingChannelType.SEARCH;

                BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
                biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPM;

                // Optional: also provide matching bidding scheme.
                biddingConfig.biddingScheme = new ManualCpmBiddingScheme();

                campaign.biddingStrategyConfiguration = biddingConfig;

                // Set the campaign budget.
                campaign.budget          = new Budget();
                campaign.budget.budgetId = budget.budgetId;

                // Set targetContentNetwork true. Other network targeting is not available
                // for Ad Exchange Buyers.
                campaign.networkSetting = new NetworkSetting();
                campaign.networkSetting.targetGoogleSearch         = false;
                campaign.networkSetting.targetSearchNetwork        = false;
                campaign.networkSetting.targetContentNetwork       = true;
                campaign.networkSetting.targetPartnerSearchNetwork = false;

                // Enable campaign for Real-time bidding.
                RealTimeBiddingSetting rtbSetting = new RealTimeBiddingSetting();
                rtbSetting.optIn = true;

                // Set the campaign settings for near-exact and near-phrase matches.
                KeywordMatchSetting keywordSetting = new KeywordMatchSetting();
                keywordSetting.optIn = false;

                campaign.settings = new Setting[] { rtbSetting, keywordSetting };

                // Optional: Set the start date.
                campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

                // Optional: Set the end date.
                campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd");

                // Optional: Set the campaign ad serving optimization status.
                campaign.adServingOptimizationStatus = AdServingOptimizationStatus.ROTATE;

                // Optional: Set the frequency cap.
                FrequencyCap frequencyCap = new FrequencyCap();
                frequencyCap.impressions = 5;
                frequencyCap.level       = Level.ADGROUP;
                frequencyCap.timeUnit    = TimeUnit.DAY;
                campaign.frequencyCap    = frequencyCap;

                // Create the operation.
                CampaignOperation operation = new CampaignOperation();
                operation.@operator = Operator.ADD;
                operation.operand   = campaign;

                operations.Add(operation);
            }

            try {
                // Add the campaign.
                CampaignReturnValue retVal = campaignService.mutate(operations.ToArray());

                // Display the results.
                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    foreach (Campaign newCampaign in retVal.value)
                    {
                        Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
                                          newCampaign.name, newCampaign.id);
                    }
                }
                else
                {
                    Console.WriteLine("No campaigns were added.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to add campaigns.", ex);
            }
        }