Creates an ad group in the specified campaign.

@param campaign the campaign to which the ad group should be attached.
@return the ad group that was created.
543496
private static AdGroup createAdGroup(
      AdWordsServicesInterface services, AdWordsSession session, Campaign campaign)
      throws RemoteException {
    AdGroupServiceInterface adGroupService = services.get(session, AdGroupServiceInterface.class);

    AdGroup group = new AdGroup();
    group.setName("Dynamic remarketing ad group");
    group.setCampaignId(campaign.getId());
    group.setStatus(AdGroupStatus.ENABLED);

    AdGroupOperation op = new AdGroupOperation();
    op.setOperand(group);
    op.setOperator(Operator.ADD);
    AdGroupReturnValue result = adGroupService.mutate(new AdGroupOperation[] {op});
    return result.getValue(0);
  }
673231
public function create($campaign)
    {
        $this->getLogger()->debug('Getting Resource Owner');
        $this->ownerId = $this->getEntityProvider()->getMe()->getId();
        $this->campaign = $campaign;

        // Rewrite parameter mismatch
        $array = $this->toArray();
        $array['name'] = $array['campaign'];
        $this->getLogger()->info('Creating Campaign ' . $this->campaign);
        $response = $this->doPost($this->url, $array);

        $this->getLogger()->debug('Passing the response to Hydrate');
        return $this->hydrate($response);
    }
496983
public function scheduleCampaign(Campaign &$campaign)
		{
			$form_data = array(
				'list_id' => $campaign->getListId(),
				'template_id' => $campaign->getTemplateId(),
				'format' => $campaign->getFormat(),
				'segmentation_id' => $campaign->getSegmentationId(),
				'seed_list_id' => $campaign->getSeedListId(),
				'suppression_list' => $campaign->getSupressionList(),
				'set_data_macro_id' => $campaign->getDataMacroId(),
				'campaign_alias' => $campaign->getAlias(),
				'target_rss' => $campaign->getRss(),
				'limit' => $campaign->getLimit(),
				'fillin_name0' => $campaign->getFillinName0(),
				'fillin_value0' => $campaign->getFillinValue0(),
				'fillin_name1' => $campaign->getFillinName1(),
				'fillin_value1' => $campaign->getFillinValue1(),
				'fillin_name2' => $campaign->getFillinName2(),
				'fillin_value2' => $campaign->getFillinValue2(),
				'fillin_name3' => $campaign->getFillinName3(),
				'fillin_value3' => $campaign->getFillinValue3(),
				'fillin_name4' => $campaign->getFillinName4(),
				'fillin_value4' => $campaign->getFillinValue4(),
				'fillin_name5' => $campaign->getFillinName5(),
				'fillin_value5' => $campaign->getFillinValue5(),
				'fillin_name6' => $campaign->getFillinName6(),
				'fillin_value6' => $campaign->getFillinValu60(),
				'fillin_name7' => $campaign->getFillinName7(),
				'fillin_value7' => $campaign->getFillinValue7(),
				'fillin_name8' => $campaign->getFillinName8(),
				'fillin_value8' => $campaign->getFillinValue8(),
				'fillin_name9' => $campaign->getFillinName9(),
				'fillin_value9' => $campaign->getFillinValue9(),
				'delivery' => $campaign->getSeedDelivery(),
				'notify_email' => $campaign->getSendNotification(),
				'start_month' => $campaign->getStartMonth(),
				'start_day' => $campaign->getStartDay(),
				'start_year' => $campaign->getStartYear(),
				'hour' => $campaign->getStartHour(),
				'minute' => $campaign->getStartMinute(),
				'end_month' => $campaign->getEndMonth(),
				'end_day' => $campaign->getEndDay(),
				'end_year' => $campaign->getEndYear(),
				'no_end_date' => $campaign->getNoEndDate(),
				'workflow_send_time' => $campaign->getWorkflowSendTime(),
				'repeat_frequency' => $campaign->getRepeatFrequency()
			);
			$this->call('schedule_deployment', $form_data);

			return TRUE;
		}
286139
public static void runExample(
      AdWordsServicesInterface adWordsServices, AdWordsSession session) throws RemoteException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService =
        adWordsServices.get(session, CampaignServiceInterface.class);

    ServiceQuery serviceQuery =
        new ServiceQuery.Builder()
            .fields(CampaignField.Id, CampaignField.Name, CampaignField.Status)
            .orderBy(CampaignField.Name)
            .limit(0, PAGE_SIZE)
            .build();

    CampaignPage page = null;
    do {
      serviceQuery.nextPage(page);
      // Get all campaigns.
      page = campaignService.query(serviceQuery.toString());

      // Display campaigns.
      if (page.getEntries() != null) {
        for (Campaign campaign : page.getEntries()) {
          System.out.printf("Campaign with name '%s' and ID %d was found.%n", campaign.getName(),
              campaign.getId());
        }
      } else {
        System.out.println("No campaigns were found.");
      }
    } while (serviceQuery.hasNext(page));
  }
631054
private static List<CampaignFeed> getCampaignFeeds(AdWordsServicesInterface adWordsServices,
      AdWordsSession session, Feed feed, int placeholderType) throws RemoteException {
    // Get the CampaignFeedService.
    CampaignFeedServiceInterface campaignFeedService =
        adWordsServices.get(session, CampaignFeedServiceInterface.class);

    String query = String.format(
        "SELECT CampaignId, MatchingFunction, PlaceholderTypes WHERE Status = 'ENABLED' "
        + "AND FeedId = %d AND PlaceholderTypes CONTAINS_ANY [%d]", feed.getId(), placeholderType);

    List<CampaignFeed> campaignFeeds = new ArrayList<>();
    int offset = 0;
    CampaignFeedPage campaignFeedPage;

    do {
      String pageQuery = String.format(query + " LIMIT %d, %d", offset, PAGE_SIZE);
      campaignFeedPage = campaignFeedService.query(pageQuery);
      if (campaignFeedPage.getEntries() != null) {
        campaignFeeds.addAll(Arrays.asList(campaignFeedPage.getEntries()));
      }
      offset += PAGE_SIZE;
    } while (offset < campaignFeedPage.getTotalNumEntries());

    return campaignFeeds;
  }
2314
private static function createAdGroup(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        Campaign $campaign
    ) {
        $adGroupService = $adWordsServices->get($session, AdGroupService::class);

        // Create ad group.
        $adGroup = new AdGroup();
        $adGroup->setCampaignId($campaign->getId());
        $adGroup->setName('Ad Group #' . uniqid());

        // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS.
        $adGroup->setAdGroupType(AdGroupType::SHOPPING_SHOWCASE_ADS);

        // Required: Set the ad group's bidding strategy configuration.
        // Note: Showcase ads require that the campaign has a ManualCpc
        // BiddingStrategyConfiguration.
        $biddingStrategyConfiguration = new BiddingStrategyConfiguration();

        // Optional: Set the bids.
        $bidAmount = new Money();
        $bidAmount->setMicroAmount(100000);
        $cpcBid = new CpcBid();
        $cpcBid->setBid($bidAmount);
        $biddingStrategyConfiguration->setBids([$cpcBid]);

        $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

        // Create operation.
        $adGroupOperation = new AdGroupOperation();
        $adGroupOperation->setOperand($adGroup);
        $adGroupOperation->setOperator(Operator::ADD);

        // Make the mutate request.
        $adGroupAddResult = $adGroupService->mutate([$adGroupOperation]);
        $adGroup = $adGroupAddResult->getValue()[0];

        return $adGroup;
    }
882817
def _CreateAdGroup(client, campaign_id):
  
  ad_group_service = client.GetService('AdGroupService')

  operations = [{
      'operator': 'ADD',
      'operand': {
          'campaignId': campaign_id,
          'adGroupType': 'SEARCH_DYNAMIC_ADS',
          'name': 'Earth to Mars Cruises #%d' % uuid.uuid4(),
          'status': 'PAUSED',
          'biddingStrategyConfiguration': {
              'bids': [{
                  'xsi_type': 'CpcBid',
                  'bid': {
                      'microAmount': '3000000'
                  },
              }]
          }
      }
  }]

  ad_group = ad_group_service.mutate(operations)['value'][0]
  ad_group_id = ad_group['id']

  print 'Ad group with ID "%d" and name "%s" was created.' % (
      ad_group_id, ad_group['name'])

  return ad_group_id
434592
public com.google.api.ads.adwords.axis.v201809.cm.CampaignSharedSet getCampaignSharedSet() {
        return campaignSharedSet;
    }
568001
public com.google.api.ads.adwords.axis.v201809.cm.AdGroupExtensionSetting getAdGroupExtensionSetting() {
        return adGroupExtensionSetting;
    }
460384
protected function getOrCreateCampaign($data)
    {
        // Create new campaign if selected
        if (is_array($data) && !empty($data['AddNewSelect']) // Explicitly click "Add to a new campaign"
            || (is_array($data) && !isset($data['Campaign']) && isset($data['NewTitle'])) // This is the only option
        ) {
            // Permission
            if (!ChangeSet::singleton()->canCreate()) {
                throw $this->validationResult(
                    _t(__CLASS__ . '.CREATE_DENIED', 'You do not have permission to create campaigns')
                );
            }

            // Check title is valid
            $title = $data['NewTitle'];
            if (empty($title)) {
                throw $this->validationResult(
                    _t(__CLASS__ . '.MISSING_TITLE', 'Campaign name is required'),
                    'NewTitle'
                );
            }

            // Prevent duplicates
            $hasExistingName = Changeset::get()
                    ->filter('Name:nocase', $title)
                    ->count() > 0;

            if ($hasExistingName) {
                throw $this->validationResult(
                    _t(
                        'SilverStripe\\CampaignAdmin\\CampaignAdmin.ERROR_DUPLICATE_NAME',
                        'Name "{Name}" already exists',
                        ['Name' => $title]
                    ),
                    'NewTitle'
                );
            }

            // Create and return
            $campaign = ChangeSet::create();
            $campaign->Name = $title;
            $campaign->write();
            return $campaign->ID;
        }

        // Get selected campaign ID
        $campaignID = null;
        if (is_array($data) && !empty($data['Campaign'])) {
            $campaignID = $data['Campaign'];
        } elseif (is_numeric($data)) {
            $campaignID = (int)$data;
        }
        if (empty($campaignID)) {
            throw $this->validationResult(_t(__CLASS__ . '.NONE_SELECTED', 'No campaign selected'));
        }
        return $campaignID;
    }
873755
public GroupEntity createNewGroup(String groupId) {
    checkAuthorization(Permissions.CREATE, Resources.GROUP, null);
    return new GroupEntity(groupId);
  }
58322
def CreateUnit(self, parent=None, value=None, bid_amount=None):
    
    unit = {
        'xsi_type': 'ProductPartition',
        'partitionType': 'UNIT'
    }

    # The root node has neither a parent nor a value.
    if parent is not None:
      unit['parentCriterionId'] = parent['id']
      unit['caseValue'] = value

    if bid_amount is not None and bid_amount > 0:
      # Note: Showcase ads require that the campaign has a ManualCpc
      # BiddingStrategyConfiguration.
      bidding_strategy_configuration = {
          'bids': [{
              'xsi_type': 'CpcBid',
              'bid': {
                  'xsi_type': 'Money',
                  'microAmount': str(bid_amount)
              }
          }]
      }

      adgroup_criterion = {
          'xsi_type': 'BiddableAdGroupCriterion',
          'biddingStrategyConfiguration': bidding_strategy_configuration
      }
    else:
      adgroup_criterion = {
          'xsi_type': 'NegativeAdGroupCriterion'
      }

    adgroup_criterion['adGroupId'] = self.adgroup_id
    adgroup_criterion['criterion'] = unit

    self.CreateAddOperation(adgroup_criterion)

    return unit
208225
public com.google.api.ads.adwords.axis.v201809.cm.AdGroup getAdGroup() {
        return adGroup;
    }
53189
public function getCampaignRevenueData(
        Campaign $campaign,
        \DateTime $dateFrom,
        \DateTime $dateTo,
        $unit,
        $dbunit,
        $cache_dir = __DIR__
    ) {
        $builder = $this->getEntityManager()->getConnection()->createQueryBuilder();
        $builder
            ->select(
                'DATE_FORMAT(DATE_ADD(date_added, INTERVAL :interval SECOND), :dbUnit) as label',
                'SUM(IFNULL(cost, 0.0))                                                as cost',
                'SUM(IFNULL(revenue, 0.0))                                             as revenue',
                'SUM(IFNULL(revenue, 0.0))-SUM(IFNULL(cost, 0.0))                      as profit'
            )
            ->from('contact_ledger')
            ->where(
                $builder->expr()->eq('campaign_id', ':campaignId'),
                $builder->expr()->gte('date_added', 'FROM_UNIXTIME(:dateFrom)'),
                $builder->expr()->lte('date_added', 'FROM_UNIXTIME(:dateTo)')
            )
            ->groupBy('label');

        // query the database
        $builder->setParameter(':interval', (new \DateTime())->getOffset(), Type::INTEGER);
        $builder->setParameter(':dbUnit', $dbunit, Type::STRING);
        $builder->setParameter(':campaignId', $campaign->getId(), Type::INTEGER);
        $builder->setParameter(':dateFrom', $dateFrom->getTimestamp(), Type::INTEGER);
        $builder->setParameter(':dateTo', $dateTo->getTimestamp(), Type::INTEGER);

        $cache = new FilesystemCache($cache_dir.'/sql');

        $stmt = $builder->getConnection()->executeCacheQuery(
            $builder->getSQL(),
            $builder->getParameters(),
            $builder->getParameterTypes(),
            new QueryCacheProfile(900, 'campaign-revenue-queries', $cache)
        );

        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $stmt->closeCursor();

        // Sort and pad-out the results to match the other charts.
        $intervalMap = [
            'H' => ['hour', 'Y-m-d H:00'],
            'd' => ['day', 'Y-m-d'],
            'W' => ['week', 'Y \w\e\e\k W'],
            'Y' => ['year', 'Y'],
            'm' => ['minute', 'Y-m-d H:i'],
            's' => ['second', 'Y-m-d H:i:s'],
        ];
        $interval    = \DateInterval::createFromDateString('1 '.$intervalMap[$unit][0]);
        $periods     = new \DatePeriod($dateFrom, $interval, $dateTo);
        $updatedData = [];
        foreach ($periods as $period) {
            $dateToCheck   = $period->format($intervalMap[$unit][1]);
            $dataKey       = array_search($dateToCheck, array_column($data, 'label'));
            $updatedData[] = [
                'label'   => $dateToCheck,
                'cost'    => (false !== $dataKey) ? $data[$dataKey]['cost'] : 0,
                'revenue' => (false !== $dataKey) ? $data[$dataKey]['revenue'] : 0,
                'profit'  => (false !== $dataKey) ? $data[$dataKey]['profit'] : 0,
            ];
        }

        return $updatedData;
    }
360097
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
      throws RemoteException {
    Budget budget = createBudget(adWordsServices, session);

    Campaign campaign = createCampaign(adWordsServices, session, budget);
    AdGroup adGroup = createAdGroup(adWordsServices, session, campaign);
    createExpandedDSA(adWordsServices, session, adGroup);
    addWebPageCriteria(adWordsServices, session, adGroup);
  }
1098487
def campaigns
      response = @@soap.getClientCampaigns(:apiKey => @apiKey, :clientID => @clientID )
      campaign_list = handle_response response.client_GetCampaignsResult
      campaign_list.collect do |campaign|  
        Campaign.new(campaign.campaignID, campaign.subject, campaign.name, campaign.sentDate, campaign.totalRecipients, :apiKey=> @apiKey)
      end
    end
809084
def _CreateCampaign(client, budget):
  
  campaign_service = client.GetService('CampaignService')

  operations = [{
      'operator': 'ADD',
      'operand': {
          'name': 'Interplanetary Cruise #%d' % uuid.uuid4(),
          # Recommendation: Set the campaign to PAUSED when creating it to
          # prevent the ads from immediately serving. Set to ENABLED once you've
          # added targeting and the ads are ready to serve.
          'status': 'PAUSED',
          'advertisingChannelType': 'SEARCH',
          'biddingStrategyConfiguration': {
              'biddingStrategyType': 'MANUAL_CPC',
          },
          'budget': budget,
          # Required: Set the campaign's Dynamic Search Ad settings.
          'settings': [{
              'xsi_type': 'DynamicSearchAdsSetting',
              # Required: Set the domain name and language.
              'domainName': 'example.com',
              'languageCode': 'en'
          }],
          # Optional: Set the start date.
          'startDate': (datetime.datetime.now() +
                        datetime.timedelta(1)).strftime('%Y%m%d'),
          # Optional: Set the end date.
          'endDate': (datetime.datetime.now() +
                      datetime.timedelta(365)).strftime('%Y%m%d'),
      }
  }]

  campaign = campaign_service.mutate(operations)['value'][0]
  campaign_id = campaign['id']

  print 'Campaign with ID "%d" and name "%s" was added.' % (
      campaign_id, campaign['name'])

  return campaign_id