public static IEnumerable<KeyValuePair<string, string>> GetSpecialistList(AdGroup grp) { var list = new Dictionary<string, string>(); using (WindowsImpersonationContextFacade impersonationContext = new WindowsImpersonationContextFacade( nc)) { var domain = new PrincipalContext(ContextType.Domain); var group = GroupPrincipal.FindByIdentity(domain, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp)); if (group != null) { var members = group.GetMembers(true); foreach (var principal in members) { var userPrincipal = UserPrincipal.FindByIdentity(domain, principal.SamAccountName); if (userPrincipal != null) { var name = MainHelper.ShortName(userPrincipal.DisplayName); var sid = userPrincipal.Sid.Value; list.Add(sid, name); } } } return list.OrderBy(x => x.Value); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to be updated.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService) user.GetService(AdWordsService.v201601.AdGroupService); // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.status = AdGroupStatus.PAUSED; adGroup.id = adGroupId; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.SET; operation.operand = adGroup; try { // Update the ad group. AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] {operation}); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroup pausedAdGroup = retVal.value[0]; Console.WriteLine("Ad group with id = '{0}' was successfully updated.", pausedAdGroup.id); } else { Console.WriteLine("No ad groups were updated."); } } catch (Exception e) { throw new System.ApplicationException("Failed to update ad group.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to be removed.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService) user.GetService( AdWordsService.v201509.AdGroupService); // Create ad group with REMOVED status. AdGroup adGroup = new AdGroup(); adGroup.id = adGroupId; adGroup.status = AdGroupStatus.REMOVED; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.operand = adGroup; operation.@operator = Operator.SET; try { // Remove the ad group. AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] {operation}); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroup removedAdGroup = retVal.value[0]; Console.WriteLine("Ad group with id = \"{0}\" and name = \"{1}\" was removed.", removedAdGroup.id, removedAdGroup.name); } else { Console.WriteLine("No ad groups were removed."); } } catch (Exception e) { throw new System.ApplicationException("Failed to remove ad group.", e); } }
public static IEnumerable<Specialist> GetSpecialistListS(AdGroup grp) { var list = new List<Specialist>(); using (WindowsImpersonationContextFacade impersonationContext = new WindowsImpersonationContextFacade( nc)) { var domain = new PrincipalContext(ContextType.Domain); var group = GroupPrincipal.FindByIdentity(domain, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp)); if (group != null) { var members = group.GetMembers(true); foreach (var principal in members) { var userPrincipal = UserPrincipal.FindByIdentity(domain, principal.SamAccountName); if (userPrincipal != null) { var fullName = userPrincipal.DisplayName; var displayName = StringHelper.ShortName(userPrincipal.DisplayName); var sid = userPrincipal.Sid.Value; list.Add(new Specialist() { SpecialistSid = sid, FullName = fullName, DisplayName = displayName }); } } } return list; } }
protected void Page_Load(object sender, EventArgs e) { loggedInAdmin = Helpers.GetLoggedInAdmin(); currentCompany = Helpers.GetCurrentCompany(); currentAdGroup = Helpers.GetCurrentAdGroup(); currentCampaign = currentAdGroup.campaign_; if (!Helpers.IsAuthorizedAdmin(loggedInAdmin, currentAdGroup.campaign_.company_)) { Response.Redirect("/status.aspx?error=notadmin"); } PopuplateBreadcrumbs(); if (!IsPostBack) { UpdateAdGroupHyperLink.NavigateUrl = "/manage/AdGroups/UpdateAdGroupDetails.aspx?adgroup_id=" + currentAdGroup.adgroup_id; CreateAdMatchesHyperLink.NavigateUrl = "/manage/AdMatches/CreateAdMatches.aspx?adgroup_id=" + currentAdGroup.adgroup_id; } PopulateDetails(); ShowAdMatches(currentAdGroup); }
public static SelectList GetUserSelectionList(AdGroup group) { Uri uri = new Uri($"{OdataServiceUri}/Ad/GetUserListByAdGroup?group={group}"); string jsonString = GetJson(uri); var model = JsonConvert.DeserializeObject<IEnumerable<KeyValuePair<string, string>>>(jsonString); return new SelectList(model, "Key", "Value"); }
protected void Page_Load(object sender, EventArgs e) { loggedInAdmin = Helpers.GetLoggedInAdmin(); current_adgroup = Helpers.GetCurrentAdGroup(); if (!Helpers.IsAuthorizedAdmin(loggedInAdmin, current_adgroup.campaign_.company_)) { Response.Redirect("/status.aspx?error=notadmin"); } if (!IsPostBack) { ShowOwnStores(); } PopuplateBreadcrumbs(); //if (current_adgroup.campaign_.company_.is_retailer == false) //{ // ShowOwnButton.Enabled = false; //} //AdGroupBudgetLabel.Text = "$" + current_adgroup.budget; //PopulateExistingRequestedAds(current_adgroup); }
public void ShowAdMatches(AdGroup current_adgroup) { foreach (AdMatch admatch in current_adgroup.AdMatchesByadgroup_) { var admatch_control = (manage.AdGroups.AdMatchUserControl)LoadControl("AdMatchUserControl.ascx"); admatch_control.admatch = admatch; AdMatchesPanel.Controls.Add(admatch_control); Literal brclear = new Literal(); brclear.Text = "<div class=\"brclear\"></div> "; AdMatchesPanel.Controls.Add(brclear); } }
protected void PopulateExistingRequestedAds(AdGroup current_adgroup) { List<RequestedAd> existing_requestedads = new List<RequestedAd>(); // Create the output table. DataTable adlist = new DataTable(); adlist.Columns.Add("store"); adlist.Columns.Add("store_id"); adlist.Columns.Add("company"); adlist.Columns.Add("company_id"); adlist.Columns.Add("title"); adlist.Columns.Add("num_wanted"); adlist.Columns.Add("daily_quota"); foreach (AdMatch admatch in current_adgroup.AdMatchesByadgroup_) { existing_requestedads.AddRange(admatch.RequestedAdsByadmatch_); } foreach (RequestedAd item in existing_requestedads) { DataRow new_row = adlist.NewRow(); new_row["store"] = item.admatch_.store_.suburb; new_row["store_id"] = item.admatch_.store_id; new_row["company"] = item.admatch_.store_.company_.name; new_row["company_id"] = item.admatch_.store_.company_id; new_row["title"] = item.uploadedad_.title; new_row["num_wanted"] = item.num_wanted; new_row["daily_quota"] = item.daily_quota; adlist.Rows.Add(new_row); } ExistingAdsRequestsGridView.DataSource = adlist; ExistingAdsRequestsGridView.DataBind(); }
public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) { hash ^= ResourceName.GetHashCode(); } if (adGroup_ != null) { hash ^= AdGroup.GetHashCode(); } if (label_ != null) { hash ^= Label.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="merchantId">The ID of the merchant center account from which to source /// product feed data.</param> /// <param name="budgetId">The ID of a shared budget to associate with the campaign.</param> /// <param name="userListId">The ID of a user list to target.</param> public void Run(AdWordsUser user, long merchantId, long budgetId, long userListId) { try { Campaign campaign = CreateCampaign(user, merchantId, budgetId); Console.WriteLine("Campaign with name '{0}' and ID {1} was added.", campaign.name, campaign.id); AdGroup adGroup = CreateAdGroup(user, campaign); Console.WriteLine("Ad group with name '{0}' and ID {1} was added.", adGroup.name, adGroup.id); AdGroupAd adGroupAd = CreateAd(user, adGroup); Console.WriteLine("Responsive display ad with ID {0} was added.", adGroupAd.ad.id); AttachUserList(user, adGroup, userListId); Console.WriteLine("User list with ID {0} was attached to ad group with ID {1}.", userListId, adGroup.id); } catch (Exception e) { throw new System.ApplicationException("Failed to create Shopping dynamic remarketing " + "campaign for the Display Network.", e); } }
/// <summary> /// Creates the Showcase ad. /// </summary> /// <param name="user">The AdWords user for which the ad is created.</param> /// <param name="adGroup">The ad group in which the ad is created.</param> /// <returns>The newly created Showcase ad.</returns> private static AdGroupAd CreateShowcaseAd(AdWordsUser user, AdGroup adGroup) { using (AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService( AdWordsService.v201802.AdGroupAdService)) { // Create the Showcase ad. ShowcaseAd showcaseAd = new ShowcaseAd(); // Required: set the ad's name, final URLs and display URL. showcaseAd.name = "Showcase ad " + ExampleUtilities.GetShortRandomString(); showcaseAd.finalUrls = new string[] { "http://example.com/showcase" }; showcaseAd.displayUrl = "example.com"; // Required: Set the ad's expanded image. Image expandedImage = new Image(); expandedImage.mediaId = UploadImage(user, "https://goo.gl/IfVlpF"); showcaseAd.expandedImage = expandedImage; // Optional: Set the collapsed image. Image collapsedImage = new Image(); collapsedImage.mediaId = UploadImage(user, "https://goo.gl/NqTxAE"); showcaseAd.collapsedImage = collapsedImage; // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroup.id; adGroupAd.ad = showcaseAd; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.operand = adGroupAd; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); return(retval.value[0]); } }
private object GetActiveDirectoryObject(AdObject obj) { switch (obj.Type) { case AdObjectType.User: AdUser user = (AdUser)obj; UserPrincipalObject upo = null; upo = DirectoryServices.GetUser(user.Identity, config.ReturnGroupMembership, config.ReturnAccessRules, config.ReturnObjectProperties); if (upo == null) { throw new AdException($"User [{user.Identity}] Was Not Found.", AdStatusType.DoesNotExist); } return(upo); case AdObjectType.Group: AdGroup group = (AdGroup)obj; GroupPrincipalObject gpo = null; gpo = DirectoryServices.GetGroup(group.Identity, config.ReturnGroupMembership, config.ReturnAccessRules, config.ReturnObjectProperties); if (gpo == null) { throw new AdException($"Group [{group.Identity}] Was Not Found.", AdStatusType.DoesNotExist); } return(gpo); case AdObjectType.OrganizationalUnit: AdOrganizationalUnit ou = (AdOrganizationalUnit)obj; OrganizationalUnitObject ouo = null; ouo = DirectoryServices.GetOrganizationalUnit(ou.Identity, config.ReturnAccessRules, config.ReturnObjectProperties); if (ouo == null) { throw new AdException($"Organizational Unit [{ou.Identity}] Was Not Found.", AdStatusType.DoesNotExist); } return(ouo); default: throw new AdException("Action [" + config.Action + "] Not Implemented For Type [" + obj.Type + "]", AdStatusType.NotSupported); } }
/// <summary> /// Creates the ad group in a Shopping campaign. /// </summary> /// <param name="user">The AdWords user for which the ad group is created.</param> /// <param name="campaign">The Shopping campaign.</param> /// <returns>The newly created ad group.</returns> private static AdGroup CreateAdGroup(AdWordsUser user, Campaign campaign) { using (AdGroupService adGroupService = (AdGroupService)user.GetService( AdWordsService.v201802.AdGroupService)) { // Create ad group. AdGroup adGroup = new AdGroup(); adGroup.campaignId = campaign.id; adGroup.name = "Ad Group #" + ExampleUtilities.GetRandomString(); // Required: Set the ad group type to SHOPPING_SHOWCASE_ADS. adGroup.adGroupType = AdGroupType.SHOPPING_SHOWCASE_ADS; // Required: Set the ad group's bidding strategy configuration. BiddingStrategyConfiguration biddingConfiguration = new BiddingStrategyConfiguration(); // Optional: Set the bids. biddingConfiguration.bids = new Bids[] { new CpcBid() { bid = new Money() { microAmount = 100000 } } }; adGroup.biddingStrategyConfiguration = biddingConfiguration; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.operand = adGroup; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation }); return(retval.value[0]); } }
/// <summary> /// Creates the ad group in a Shopping campaign. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">The campaign ID.</param> /// <returns>The ad group.</returns> private static AdGroup CreateAdGroup(AdWordsUser user, long campaignId) { AdGroupService adGroupService = (AdGroupService)user.GetService( AdWordsService.v201710.AdGroupService); // Create ad group. AdGroup adGroup = new AdGroup(); adGroup.campaignId = campaignId; adGroup.name = "Ad Group #" + ExampleUtilities.GetRandomString(); // Create operation. AdGroupOperation operation = new AdGroupOperation(); operation.operand = adGroup; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation }); adGroupService.Close(); return(retval.value[0]); }
/// <summary> /// Creates the Product Ad. /// </summary> /// <param name="adGroupAdService">The AdGroupAdService instance.</param> /// <param name="adGroup">The ad group.</param> /// <returns>The Product Ad.</returns> private static AdGroupAd CreateProductAd(AdGroupAdService adGroupAdService, AdGroup adGroup) { // Create product ad. ProductAd productAd = new ProductAd(); // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroup.id; adGroupAd.ad = productAd; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.operand = adGroupAd; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); return(retval.value[0]); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="budgetId">The budget id.</param> /// <param name="merchantId">The Merchant Center account ID.</param> /// <param name="createDefaultPartition">If set to true, a default /// partition will be created. If running the AddProductPartition.cs /// example right after this example, make sure this stays set to /// false.</param> public void Run(AdWordsUser user, long budgetId, long merchantId, bool createDefaultPartition) { try { Campaign campaign = CreateCampaign(user, budgetId, merchantId); Console.WriteLine("Campaign with name '{0}' and ID '{1}' was added.", campaign.name, campaign.id); AdGroup adGroup = CreateAdGroup(user, campaign.id); Console.WriteLine("Ad group with name '{0}' and ID '{1}' was added.", adGroup.name, adGroup.id); AdGroupAd adGroupAd = CreateProductAd(user, adGroup.id); Console.WriteLine("Product ad with ID {0}' was added.", adGroupAd.ad.id); if (createDefaultPartition) { CreateDefaultPartitionTree(user, adGroup.id); } } catch (Exception e) { throw new System.ApplicationException("Failed to create shopping campaign.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to be updated.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201603.AdGroupService); // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.status = AdGroupStatus.PAUSED; adGroup.id = adGroupId; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.SET; operation.operand = adGroup; try { // Update the ad group. AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] { operation }); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroup pausedAdGroup = retVal.value[0]; Console.WriteLine("Ad group with id = '{0}' was successfully updated.", pausedAdGroup.id); } else { Console.WriteLine("No ad groups were updated."); } } catch (Exception e) { throw new System.ApplicationException("Failed to update ad group.", e); } }
/// <summary> /// Builds the operations for creating ad groups within a campaign. /// </summary> /// <param name="campaignId">ID of the campaign for which ad groups are /// created.</param> /// <returns>A list of operations for creating ad groups.</returns> private static List <AdGroupOperation> BuildAdGroupOperations(long campaignId) { List <AdGroupOperation> operations = new List <AdGroupOperation>(); for (int i = 0; i < NUMBER_OF_ADGROUPS_TO_ADD; i++) { AdGroup adGroup = new AdGroup() { campaignId = campaignId, id = NextId(), name = "Batch Ad Group # " + ExampleUtilities.GetRandomString(), biddingStrategyConfiguration = new BiddingStrategyConfiguration() { bids = new Bids[] { new CpcBid() { bid = new Money() { microAmount = 10000000L } } } } }; AdGroupOperation operation = new AdGroupOperation() { operand = adGroup, @operator = Operator.ADD }; operations.Add(operation); } return(operations); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to be removed.</param> public void Run(AdWordsUser user, long adGroupId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService)user.GetService( AdWordsService.v201502.AdGroupService); // Create ad group with REMOVED status. AdGroup adGroup = new AdGroup(); adGroup.id = adGroupId; adGroup.status = AdGroupStatus.REMOVED; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.operand = adGroup; operation.@operator = Operator.SET; try { // Remove the ad group. AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] { operation }); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroup removedAdGroup = retVal.value[0]; Console.WriteLine("Ad group with id = \"{0}\" was renamed to \"{1}\" and removed.", removedAdGroup.id, removedAdGroup.name); } else { Console.WriteLine("No ad groups were removed."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to remove ad group.", ex); } }
/// <summary> /// 获取指定广告活动下的所有AdGroup信息 /// </summary> /// <param name="userId">用户编号</param> /// <param name="accountId">账户编号</param> /// <param name="campaignId">活动编号</param> /// <returns>返回执行后的结果</returns> public IExecuteResult GetAdGroups(uint userId, ulong accountId, ulong campaignId) { if (userId == 0) { return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal user id")); } if (accountId == 0) { return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal account id")); } if (campaignId == 0) { return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal campaign id")); } try { //获取参数的值 object[] parameterValues = new object[] { campaignId, accountId, userId }; DataTable dt = _slaveDB.SpExecuteTable(SpName.SpGetAdGroups, ParametersObject.GetAdGroups, parameterValues); if (dt.Rows.Count == 0) { return(ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpGetAdGroups + ":Executed count = 0")); } AdGroup[] adGroups = new AdGroup[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { adGroups[i] = _convertor.ConvertToDomain(dt.Rows[i]); } return(ExecuteResult.Succeed(adGroups)); } catch (Exception ex) { _tracing.Error(ex, null); return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message)); } }
// Create and Modify Group private StartPlanEnvelope GetPlanEnvelope(string identity, AdGroup group) { StartPlanEnvelope pe = GetPlanEnvelope(identity); if (group != null) { if (!string.IsNullOrWhiteSpace(group.Name)) { pe.DynamicParameters.Add(@"name", group.Name); } if (!string.IsNullOrWhiteSpace(group.Description)) { pe.DynamicParameters.Add(@"description", group.Description); } if (!string.IsNullOrWhiteSpace(group.SamAccountName)) { pe.DynamicParameters.Add(@"samaccountname", group.SamAccountName); } if (group.Scope != null) { pe.DynamicParameters.Add(@"scope", group.Scope.ToString()); } if (group.IsSecurityGroup != null) { pe.DynamicParameters.Add(@"securitygroup", group.IsSecurityGroup.ToString()); } if (group.ManagedBy != null) { pe.DynamicParameters.Add(@"managedby", group.ManagedBy); } AddPropertiesToPlan(pe, group.Properties); } return(pe); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="budgetId">The budget id.</param> /// <param name="merchantId">The Merchant Center account ID.</param> public void Run(AdWordsUser user, long budgetId, long merchantId) { try { Campaign campaign = CreateCampaign(user, budgetId, merchantId); Console.WriteLine("Campaign with name '{0}' and ID '{1}' was added.", campaign.name, campaign.id); AdGroup adGroup = CreateAdGroup(user, campaign); Console.WriteLine("Ad group with name '{0}' and ID '{1}' was added.", adGroup.name, adGroup.id); AdGroupAd adGroupAd = CreateShowcaseAd(user, adGroup); Console.WriteLine("Showcase ad with ID '{0}' was added.", adGroupAd.ad.id); ProductPartitionTree partitionTree = CreateProductPartition(user, adGroup.id); Console.WriteLine("Final tree: {0}", partitionTree); } catch (Exception e) { throw new System.ApplicationException( "Failed to create shopping campaign for " + "showcase ads.", e); } }
/// <summary> /// Creates an ad group in the specified campaign. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaign">The campaign to which the ad group should be attached.</param> /// <returns>The ad group that was created.</returns> private static AdGroup CreateAdGroup(AdWordsUser user, Campaign campaign) { using (AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201806.AdGroupService)) { AdGroup group = new AdGroup { name = "Dynamic remarketing ad group", campaignId = campaign.id, status = AdGroupStatus.ENABLED }; AdGroupOperation op = new AdGroupOperation { operand = group, @operator = Operator.ADD }; AdGroupReturnValue result = adGroupService.mutate(new AdGroupOperation[] { op }); return(result.value[0]); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to be updated.</param> /// <param name="bidMicroAmount">The CPC bid amount in micros.</param> public void Run(AdWordsUser user, long adGroupId, long?bidMicroAmount) { using (AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201710.AdGroupService)) { // Create an ad group with the specified ID. AdGroup adGroup = new AdGroup(); adGroup.id = adGroupId; // Pause the ad group. adGroup.status = AdGroupStatus.PAUSED; // Update the CPC bid if specified. if (bidMicroAmount != null) { BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration(); Money cpcBidMoney = new Money(); cpcBidMoney.microAmount = bidMicroAmount.Value; CpcBid cpcBid = new CpcBid(); cpcBid.bid = cpcBidMoney; biddingStrategyConfiguration.bids = new Bids[] { cpcBid }; adGroup.biddingStrategyConfiguration = biddingStrategyConfiguration; } // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.SET; operation.operand = adGroup; try { // Update the ad group. AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] { operation }); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { AdGroup adGroupResult = retVal.value[0]; BiddingStrategyConfiguration bsConfig = adGroupResult.biddingStrategyConfiguration; // Find the CpcBid in the bidding strategy configuration's bids collection. long cpcBidMicros = 0L; if (bsConfig != null && bsConfig.bids != null) { foreach (Bids bid in bsConfig.bids) { if (bid is CpcBid) { cpcBidMicros = ((CpcBid)bid).bid.microAmount; break; } } } Console.WriteLine("Ad group with ID {0} and name '{1}' updated to have status '{2}'" + " and CPC bid {3}", adGroupResult.id, adGroupResult.name, adGroupResult.status, cpcBidMicros); } else { Console.WriteLine("No ad groups were updated."); } } catch (Exception e) { throw new System.ApplicationException("Failed to update ad group.", e); } } }
public AdUserGroup(AdGroup grp, string sid) { Group = grp; Sid = sid; }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to which experiments are /// added.</param> /// <param name="adGroupId">Id of the ad group to which experiments are /// added.</param> /// <param name="criterionId">Id of the criterion for which experiments /// are added.</param> public void Run(AdWordsUser user, long campaignId, long adGroupId, long criterionId) { // Get the ExperimentService. ExperimentService experimentService = (ExperimentService)user.GetService(AdWordsService.v201607.ExperimentService); // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201607.AdGroupService); // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService)user.GetService(AdWordsService.v201607.AdGroupCriterionService); // Create the experiment. Experiment experiment = new Experiment(); experiment.campaignId = campaignId; experiment.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(); experiment.queryPercentage = 10; experiment.startDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss"); // Optional: Set the end date. experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss"); // Optional: Set the status. experiment.status = ExperimentStatus.ENABLED; // Create the operation. ExperimentOperation experimentOperation = new ExperimentOperation(); experimentOperation.@operator = Operator.ADD; experimentOperation.operand = experiment; try { // Add the experiment. ExperimentReturnValue experimentRetVal = experimentService.mutate( new ExperimentOperation[] { experimentOperation }); // Display the results. if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value. Length > 0) { long experimentId = 0; Experiment newExperiment = experimentRetVal.value[0]; Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n", newExperiment.name, newExperiment.id); experimentId = newExperiment.id; // Set ad group for the experiment. AdGroup adGroup = new AdGroup(); adGroup.id = adGroupId; // Create experiment bid multiplier rule that will modify ad group bid // for the experiment. ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier = new ManualCPCAdGroupExperimentBidMultipliers(); adGroupBidMultiplier.maxCpcMultiplier = new BidMultiplier(); adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5; // Set experiment data to the ad group. AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData(); adGroupExperimentData.experimentId = experimentId; adGroupExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED; adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier; adGroup.experimentData = adGroupExperimentData; // Create the operation. AdGroupOperation adGroupOperation = new AdGroupOperation(); adGroupOperation.operand = adGroup; adGroupOperation.@operator = Operator.SET; // Update the ad group. AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] { adGroupOperation }); // Display the results. if (adGroupRetVal != null && adGroupRetVal.value != null && adGroupRetVal.value.Length > 0) { AdGroup updatedAdGroup = adGroupRetVal.value[0]; Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " + "was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id, updatedAdGroup.status); } else { Console.WriteLine("No ad groups were updated."); } // Set ad group criteria for the experiment. Criterion criterion = new Criterion(); criterion.id = criterionId; BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion(); adGroupCriterion.adGroupId = adGroupId; adGroupCriterion.criterion = criterion; // Create experiment bid multiplier rule that will modify criterion bid // for the experiment. ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier = new ManualCPCAdGroupCriterionExperimentBidMultiplier(); bidMultiplier.maxCpcMultiplier = new BidMultiplier(); bidMultiplier.maxCpcMultiplier.multiplier = 1.5; // Set experiment data to the criterion. BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData = new BiddableAdGroupCriterionExperimentData(); adGroupCriterionExperimentData.experimentId = experimentId; adGroupCriterionExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED; adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier; adGroupCriterion.experimentData = adGroupCriterionExperimentData; // Create the operation. AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation(); adGroupCriterionOperation.operand = adGroupCriterion; adGroupCriterionOperation.@operator = Operator.SET; // Update the ad group criteria. AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate( new AdGroupCriterionOperation[] { adGroupCriterionOperation }); // Display the results. if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null && adGroupCriterionRetVal.value.Length > 0) { AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0]; Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = " + "\"{1}\" and type = \"{2}\" was updated for the experiment.\n", updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id, updatedAdGroupCriterion.criterion.CriterionType); } else { Console.WriteLine("No ad group criteria were updated."); } } else { Console.WriteLine("No experiments were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add experiment.", e); } }
/// <summary> /// Creates an ad group. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">The campaign ID.</param> /// <returns>the newly created ad group.</returns> private static AdGroup CreateAdGroup(AdWordsUser user, long campaignId) { using (AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201802.AdGroupService)) { // Create the ad group. AdGroup adGroup = new AdGroup { // Required: Set the ad group's type to Dynamic Search Ads. adGroupType = AdGroupType.SEARCH_DYNAMIC_ADS, name = string.Format("Earth to Mars Cruises #{0}", ExampleUtilities.GetRandomString()), campaignId = campaignId, status = AdGroupStatus.PAUSED, // Recommended: Set a tracking URL template for your ad group if you want to use // URL tracking software. trackingUrlTemplate = "http://tracker.example.com/traveltracker/{escapedlpurl}" }; // Set the ad group bids. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); CpcBid cpcBid = new CpcBid { bid = new Money { microAmount = 3000000 } }; biddingConfig.bids = new Bids[] { cpcBid }; adGroup.biddingStrategyConfiguration = biddingConfig; // Create the operation. AdGroupOperation operation = new AdGroupOperation { @operator = Operator.ADD, operand = adGroup }; try { // Create the ad group. AdGroupReturnValue retVal = adGroupService.mutate(new AdGroupOperation[] { operation }); // Display the results. AdGroup newAdGroup = retVal.value[0]; Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.", newAdGroup.id, newAdGroup.name); return(newAdGroup); } catch (Exception e) { throw new System.ApplicationException("Failed to create ad group.", e); } } }
public void AddToAdGroup(AdGroup adGroup) { base.AddObject("AdGroup", adGroup); }
/// <summary> /// Builds the operations for creating ad groups within a campaign. /// </summary> /// <param name="campaignId">ID of the campaign for which ad groups are /// created.</param> /// <returns>A list of operations for creating ad groups.</returns> private static List<AdGroupOperation> BuildAdGroupOperations(long campaignId) { List<AdGroupOperation> operations = new List<AdGroupOperation>(); for (int i = 0; i < NUMBER_OF_ADGROUPS_TO_ADD; i++) { AdGroup adGroup = new AdGroup() { campaignId = campaignId, id = NextId(), name = "Batch Ad Group # " + ExampleUtilities.GetRandomString(), biddingStrategyConfiguration = new BiddingStrategyConfiguration() { bids = new Bids[] { new CpcBid() { bid = new Money() { microAmount = 10000000L } } } } }; AdGroupOperation operation = new AdGroupOperation() { operand = adGroup, @operator = Operator.ADD }; operations.Add(operation); } return operations; }
/// <summary> /// Show all Stores in the system. /// TODO: Replace this button with a proper search module. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> //protected void ShowAllButton_Click(object sender, EventArgs e) //{ // StoresGridView.DataSource = Store.GetStores().Where(s => s.company_id != current_adgroup.campaign_.company_id); // StoresGridView.DataBind(); // if (current_adgroup.campaign_.company_.is_retailer == true) // { // RefreshAdLibrary(current_adgroup, 5); // } // else // { // RefreshAdLibrary(current_adgroup, 10); // } //} private void RefreshAdLibrary(AdGroup current_adgroup, int ad_price) { //PriceLabel.Text = ad_price.ToString() + "c"; AdLibraryListView.DataSource = current_adgroup.campaign_.company_.UploadedAdsBycompany_.Where(p => p.is_active == true); AdLibraryListView.DataBind(); }
internal override void ProcessMappingsFromRowValues(RowValues values) { AdGroup = new AdGroup { AdDistribution = 0 }; values.ConvertToEntity(this, Mappings); QualityScoreData = QualityScoreData.ReadFromRowValuesOrNull(values); PerformanceData = PerformanceData.ReadFromRowValuesOrNull(values); }
public AdUserGroup(AdGroup grp, string sid, string name) { Group = grp; Sid = sid; Name = name; }
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); }
public static string GetSidByAdGroup(AdGroup grp) { return(GetList().Single(g => g.Group == grp).Sid); }
public async override Task RunAsync(AuthorizationData authorizationData) { try { Service = new ServiceClient <ICampaignManagementService>(authorizationData); // Specify a campaign. var campaign = new Campaign { Name = "Women's Shoes" + DateTime.UtcNow, Description = "Red shoes line.", BudgetType = BudgetLimitType.MonthlyBudgetSpendUntilDepleted, MonthlyBudget = 1000.00, TimeZone = "PacificTimeUSCanadaTijuana", DaylightSaving = true }; // Specify an ad group. var adGroup = new AdGroup { Name = "Women's Red Shoe Sale", AdDistribution = AdDistribution.Search, BiddingModel = BiddingModel.Keyword, PricingModel = PricingModel.Cpc, StartDate = null, EndDate = new Date { Month = 12, Day = 31, Year = 2015 }, ExactMatchBid = new Bid { Amount = 0.09 }, PhraseMatchBid = new Bid { Amount = 0.07 }, Language = "English" }; // Add the campaign and ad group var campaignIds = (long[]) await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign }); var adGroupIds = (long[]) await AddAdGroupsAsync(campaignIds[0], new[] { adGroup }); // Print the new assigned campaign and ad group identifiers PrintCampaignIdentifiers(campaignIds); PrintAdGroupIdentifiers(adGroupIds); // Bing Ads API Version 9 supports both Target and Target2 objects. You should use Target2. // This example compares Target and Target2, and demonstrates the impact of updating the // DayTimeTarget, IntentOption, and RadiusTarget2 nested in a Target2 object. var campaignTarget = new Target { Name = "My Campaign Target", Day = new DayTarget { Bids = new[] { new DayTargetBid { BidAdjustment = 10, Day = Day.Friday } } }, Hour = new HourTarget { Bids = new[] { new HourTargetBid { BidAdjustment = 10, Hour = HourRange.ElevenAMToTwoPM } } }, Location = new LocationTarget { HasPhysicalIntent = true, MetroAreaTarget = new MetroAreaTarget { Bids = new List <MetroAreaTargetBid> { new MetroAreaTargetBid { BidAdjustment = 15, MetroArea = "Seattle-Tacoma, WA, WA US", IsExcluded = false } } }, RadiusTarget = new RadiusTarget { Bids = new[] { new RadiusTargetBid { BidAdjustment = 50, LatitudeDegrees = 47.755367, LongitudeDegrees = -122.091827, Radius = 5 } } } } }; var adGroupTarget = new Target { Name = "My Ad Group Target", Hour = new HourTarget { Bids = new[] { new HourTargetBid { BidAdjustment = 10, Hour = HourRange.SixPMToElevenPM } } } }; // Each customer has a target library that can be used to set up targeting for any campaign // or ad group within the specified customer. // Add a target to the library and associate it with the campaign. var campaignTargetId = (await AddTargetsToLibraryAsync(new[] { campaignTarget }))[0]; OutputStatusMessage(String.Format("Added Target Id: {0}\n", campaignTargetId)); SetTargetToCampaignAsync(campaignIds[0], campaignTargetId); OutputStatusMessage(String.Format("Associated CampaignId {0} with TargetId {1}.\n", campaignIds[0], campaignTargetId)); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get Campaign Target: \n"); var targets = await GetTargetsByIdsAsync(new[] { campaignTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get Campaign Target2: \n"); var targets2 = await GetTargetsByIds2Async(new[] { campaignTargetId }); PrintTarget2(targets2[0]); // Add a target to the library and associate it with the ad group. var adGroupTargetId = (await AddTargetsToLibraryAsync(new[] { adGroupTarget }))[0]; OutputStatusMessage(String.Format("Added Target Id: {0}\n", adGroupTargetId)); SetTargetToAdGroupAsync(adGroupIds[0], adGroupTargetId); OutputStatusMessage(String.Format("Associated AdGroupId {0} with TargetId {1}.\n", adGroupIds[0], adGroupTargetId)); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get AdGroup Target: \n"); targets = await GetTargetsByIdsAsync(new[] { adGroupTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get AdGroup Target2: \n"); targets2 = await GetTargetsByIds2Async(new[] { adGroupTargetId }); PrintTarget2(targets2[0]); // Update the ad group's target as a Target2 object with additional target types. // Existing target types such as DayTime, Location, and Radius must be specified // or they will not be included in the updated target. var target2 = new Target2 { Id = adGroupTargetId, Name = "My Target2", Age = new AgeTarget { Bids = new[] { new AgeTargetBid { BidAdjustment = 10, Age = AgeRange.EighteenToTwentyFive } } }, DayTime = new DayTimeTarget { Bids = new[] { new DayTimeTargetBid { BidAdjustment = 10, Day = Day.Friday, FromHour = 1, ToHour = 12, FromMinute = Minute.Zero, ToMinute = Minute.FortyFive } } }, DeviceOS = new DeviceOSTarget { Bids = new[] { new DeviceOSTargetBid { BidAdjustment = 20, DeviceName = "Tablets", } }, }, Gender = new GenderTarget { Bids = new[] { new GenderTargetBid { BidAdjustment = 10, Gender = GenderType.Female } } }, Location = new LocationTarget2 { IntentOption = IntentOption.PeopleSearchingForOrViewingPages, CountryTarget = new CountryTarget { Bids = new[] { new CountryTargetBid { BidAdjustment = 10, CountryAndRegion = "US", IsExcluded = false } } }, MetroAreaTarget = new MetroAreaTarget { Bids = new List <MetroAreaTargetBid> { new MetroAreaTargetBid { BidAdjustment = 15, MetroArea = "Seattle-Tacoma, WA, WA US", IsExcluded = false } } }, PostalCodeTarget = new PostalCodeTarget { Bids = new[] { new PostalCodeTargetBid { // Bid adjustments are not allowed for location exclusions. // If IsExcluded is true, this element will be ignored. BidAdjustment = 10, PostalCode = "98052, WA US", IsExcluded = true } } }, RadiusTarget = new RadiusTarget2 { Bids = new[] { new RadiusTargetBid2 { BidAdjustment = 50, LatitudeDegrees = 47.755367, LongitudeDegrees = -122.091827, Radius = 11, RadiusUnit = DistanceUnit.Kilometers } } } } }; // Update the same identified target as a Target2 object. // Going forward when getting the specified target Id, the Day and Hour elements of the legacy // Target object will be nil, since the target is being updated with a DayTime target. UpdateTargetsInLibrary2Async(new[] { target2 }); OutputStatusMessage("Updated the ad group level target as a Target2 object.\n"); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get Campaign Target: \n"); targets = await GetTargetsByIdsAsync(new[] { campaignTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get Campaign Target2: \n"); targets2 = await GetTargetsByIds2Async(new[] { campaignTargetId }); PrintTarget2(targets2[0]); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get AdGroup Target: \n"); targets = await GetTargetsByIdsAsync(new[] { adGroupTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get AdGroup Target2: \n"); targets2 = await GetTargetsByIds2Async(new[] { adGroupTargetId }); PrintTarget2(targets2[0]); // Get all new and existing targets in the customer library, whether or not they are // associated with campaigns or ad groups. var allTargetsInfo = await GetTargetsInfoFromLibraryAsync(); OutputStatusMessage("All target identifiers and names from the customer library: \n"); PrintTargetsInfo(allTargetsInfo); // Delete the campaign, ad group, and targets that were previously added. // DeleteCampaigns would remove the campaign and ad group, as well as the association // between ad groups and campaigns. To explicitly delete the association between an entity // and the target, use DeleteTargetFromCampaign and DeleteTargetFromAdGroup respectively. DeleteTargetFromCampaignAsync(campaignIds[0]); DeleteTargetFromAdGroupAsync(adGroupIds[0]); DeleteCampaignsAsync(authorizationData.AccountId, new[] { campaignIds[0] }); OutputStatusMessage(String.Format("Deleted CampaignId {0}\n", campaignIds[0])); // DeleteCampaigns deletes the association between the campaign and target, but does not // delete the target from the customer library. // Call the DeleteTargetsFromLibrary operation for each target that you want to delete. // You must specify an array with exactly one item. DeleteTargetsFromLibraryAsync(new[] { campaignTargetId }); OutputStatusMessage(String.Format("Deleted TargetId {0}\n", campaignTargetId)); DeleteTargetsFromLibraryAsync(new[] { adGroupTargetId }); OutputStatusMessage(String.Format("Deleted TargetId {0}\n", adGroupTargetId)); } // 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); } }
public static MailAddress[] GetRecipientsFromAdGroup(AdGroup group) { var list = new List<MailAddress>(); using (WindowsImpersonationContextFacade impersonationContext = new WindowsImpersonationContextFacade( nc)) { string sid = AdUserGroup.GetSidByAdGroup(group); PrincipalContext ctx = new PrincipalContext(ContextType.Domain); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Sid, sid); if (grp != null) { foreach (Principal p in grp.GetMembers(true)) { string email = new Employee(p.Sid.Value).Email; if (String.IsNullOrEmpty(email)) continue; list.Add(new MailAddress(email)); } grp.Dispose(); } ctx.Dispose(); return list.ToArray(); } }
/// <summary> /// Creates the ad group in a Shopping campaign. /// </summary> /// <param name="adGroupService">The AdGroupService instance.</param> /// <param name="campaign">The Shopping campaign.</param> /// <returns>The ad group.</returns> private static AdGroup CreateAdGroup(AdGroupService adGroupService, Campaign campaign) { // Create ad group. AdGroup adGroup = new AdGroup(); adGroup.campaignId = campaign.id; adGroup.name = "Ad Group #" + ExampleUtilities.GetRandomString(); // Create operation. AdGroupOperation operation = new AdGroupOperation(); operation.operand = adGroup; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupReturnValue retval = adGroupService.mutate(new AdGroupOperation[] { operation }); return retval.value[0]; }
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">Id of the campaign to which experiments are /// added.</param> /// <param name="adGroupId">Id of the ad group to which experiments are /// added.</param> /// <param name="criterionId">Id of the criterion for which experiments /// are added.</param> public void Run(AdWordsUser user, long campaignId, long adGroupId, long criterionId) { // Get the ExperimentService. ExperimentService experimentService = (ExperimentService) user.GetService(AdWordsService.v201601.ExperimentService); // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService) user.GetService(AdWordsService.v201601.AdGroupService); // Get the AdGroupCriterionService. AdGroupCriterionService adGroupCriterionService = (AdGroupCriterionService) user.GetService(AdWordsService.v201601.AdGroupCriterionService); // Create the experiment. Experiment experiment = new Experiment(); experiment.campaignId = campaignId; experiment.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(); experiment.queryPercentage = 10; experiment.startDateTime = DateTime.Now.AddDays(1).ToString("yyyyMMdd HHmmss"); // Optional: Set the end date. experiment.endDateTime = DateTime.Now.AddDays(30).ToString("yyyyMMdd HHmmss"); // Optional: Set the status. experiment.status = ExperimentStatus.ENABLED; // Create the operation. ExperimentOperation experimentOperation = new ExperimentOperation(); experimentOperation.@operator = Operator.ADD; experimentOperation.operand = experiment; try { // Add the experiment. ExperimentReturnValue experimentRetVal = experimentService.mutate( new ExperimentOperation[] {experimentOperation}); // Display the results. if (experimentRetVal != null && experimentRetVal.value != null && experimentRetVal.value. Length > 0) { long experimentId = 0; Experiment newExperiment = experimentRetVal.value[0]; Console.WriteLine("Experiment with name = \"{0}\" and id = \"{1}\" was added.\n", newExperiment.name, newExperiment.id); experimentId = newExperiment.id; // Set ad group for the experiment. AdGroup adGroup = new AdGroup(); adGroup.id = adGroupId; // Create experiment bid multiplier rule that will modify ad group bid // for the experiment. ManualCPCAdGroupExperimentBidMultipliers adGroupBidMultiplier = new ManualCPCAdGroupExperimentBidMultipliers(); adGroupBidMultiplier.maxCpcMultiplier = new BidMultiplier(); adGroupBidMultiplier.maxCpcMultiplier.multiplier = 1.5; // Set experiment data to the ad group. AdGroupExperimentData adGroupExperimentData = new AdGroupExperimentData(); adGroupExperimentData.experimentId = experimentId; adGroupExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED; adGroupExperimentData.experimentBidMultipliers = adGroupBidMultiplier; adGroup.experimentData = adGroupExperimentData; // Create the operation. AdGroupOperation adGroupOperation = new AdGroupOperation(); adGroupOperation.operand = adGroup; adGroupOperation.@operator = Operator.SET; // Update the ad group. AdGroupReturnValue adGroupRetVal = adGroupService.mutate(new AdGroupOperation[] { adGroupOperation}); // Display the results. if (adGroupRetVal != null && adGroupRetVal.value != null && adGroupRetVal.value.Length > 0) { AdGroup updatedAdGroup = adGroupRetVal.value[0]; Console.WriteLine("Ad group with name = \"{0}\", id = \"{1}\" and status = \"{2}\" " + "was updated for the experiment.\n", updatedAdGroup.name, updatedAdGroup.id, updatedAdGroup.status); } else { Console.WriteLine("No ad groups were updated."); } // Set ad group criteria for the experiment. Criterion criterion = new Criterion(); criterion.id = criterionId; BiddableAdGroupCriterion adGroupCriterion = new BiddableAdGroupCriterion(); adGroupCriterion.adGroupId = adGroupId; adGroupCriterion.criterion = criterion; // Create experiment bid multiplier rule that will modify criterion bid // for the experiment. ManualCPCAdGroupCriterionExperimentBidMultiplier bidMultiplier = new ManualCPCAdGroupCriterionExperimentBidMultiplier(); bidMultiplier.maxCpcMultiplier = new BidMultiplier(); bidMultiplier.maxCpcMultiplier.multiplier = 1.5; // Set experiment data to the criterion. BiddableAdGroupCriterionExperimentData adGroupCriterionExperimentData = new BiddableAdGroupCriterionExperimentData(); adGroupCriterionExperimentData.experimentId = experimentId; adGroupCriterionExperimentData.experimentDeltaStatus = ExperimentDeltaStatus.MODIFIED; adGroupCriterionExperimentData.experimentBidMultiplier = bidMultiplier; adGroupCriterion.experimentData = adGroupCriterionExperimentData; // Create the operation. AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation(); adGroupCriterionOperation.operand = adGroupCriterion; adGroupCriterionOperation.@operator = Operator.SET; // Update the ad group criteria. AdGroupCriterionReturnValue adGroupCriterionRetVal = adGroupCriterionService.mutate( new AdGroupCriterionOperation[] {adGroupCriterionOperation}); // Display the results. if (adGroupCriterionRetVal != null && adGroupCriterionRetVal.value != null && adGroupCriterionRetVal.value.Length > 0) { AdGroupCriterion updatedAdGroupCriterion = adGroupCriterionRetVal.value[0]; Console.WriteLine("Ad group criterion with ad group id = \"{0}\", criterion id = " + "\"{1}\" and type = \"{2}\" was updated for the experiment.\n", updatedAdGroupCriterion.adGroupId, updatedAdGroupCriterion.criterion.id, updatedAdGroupCriterion.criterion.CriterionType); } else { Console.WriteLine("No ad group criteria were updated."); } } else { Console.WriteLine("No experiments were added."); } } catch (Exception e) { throw new System.ApplicationException("Failed to add experiment.", e); } }
/// <summary> /// Creates the Product Ad. /// </summary> /// <param name="adGroupAdService">The AdGroupAdService instance.</param> /// <param name="adGroup">The ad group.</param> /// <returns>The Product Ad.</returns> private static AdGroupAd CreateProductAd(AdGroupAdService adGroupAdService, AdGroup adGroup) { // Create product ad. ProductAd productAd = new ProductAd(); // Create ad group ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = adGroup.id; adGroupAd.ad = productAd; // Create operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.operand = adGroupAd; operation.@operator = Operator.ADD; // Make the mutate request. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); return retval.value[0]; }
/// <summary> /// Creates an ad for serving dynamic content in a remarketing campaign. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroup">The ad group under which to create the ad.</param> /// <returns>The ad that was created.</returns> private static AdGroupAd CreateAd(AdWordsUser user, AdGroup adGroup) { using (AdGroupAdService adService = (AdGroupAdService)user.GetService(AdWordsService.v201806.AdGroupAdService)) { ResponsiveDisplayAd ad = new ResponsiveDisplayAd { // This ad format does not allow the creation of an image using the // Image.data field. An image must first be created using the MediaService, // and Image.mediaId must be populated when creating the ad. marketingImage = UploadImage(user, "https://goo.gl/3b9Wfh"), shortHeadline = "Travel", longHeadline = "Travel the World", description = "Take to the air!", businessName = "Interplanetary Cruises", finalUrls = new string[] { "http://www.example.com/" }, // Optional: Call to action text. // Valid texts: https://support.google.com/adwords/answer/7005917 callToActionText = "Apply Now", // Optional: Set dynamic display ad settings, composed of landscape logo // image, promotion text, and price prefix. dynamicDisplayAdSettings = CreateDynamicDisplayAdSettings(user), // Optional: Create a logo image and set it to the ad. logoImage = UploadImage(user, "https://goo.gl/mtt54n"), // Optional: Create a square marketing image and set it to the ad. squareMarketingImage = UploadImage(user, "https://goo.gl/mtt54n") }; // Whitelisted accounts only: Set color settings using hexadecimal values. // Set allowFlexibleColor to false if you want your ads to render by always // using your colors strictly. // ad.mainColor = "#0000ff"; // ad.accentColor = "#ffff00"; // ad.allowFlexibleColor = false; // Whitelisted accounts only: Set the format setting that the ad will be // served in. // ad.formatSetting = DisplayAdFormatSetting.NON_NATIVE; AdGroupAd adGroupAd = new AdGroupAd { ad = ad, adGroupId = adGroup.id }; AdGroupAdOperation op = new AdGroupAdOperation { operand = adGroupAd, @operator = Operator.ADD }; AdGroupAdReturnValue result = adService.mutate(new AdGroupAdOperation[] { op }); return(result.value[0]); } }
/// <summary> /// Outputs the AdGroup. /// </summary> protected void OutputAdGroup(AdGroup adGroup) { if (adGroup != null) { OutputStatusMessage(string.Format("AdDistribution: {0}", adGroup.AdDistribution)); OutputStatusMessage(string.Format("AdRotation Type: {0}", adGroup.AdRotation != null ? adGroup.AdRotation.Type : null)); OutputStatusMessage(string.Format("BiddingModel: {0}", adGroup.BiddingModel)); OutputStatusMessage("ForwardCompatibilityMap: "); if (adGroup.ForwardCompatibilityMap != null) { foreach (var pair in adGroup.ForwardCompatibilityMap) { OutputStatusMessage(string.Format("Key: {0}", pair.Key)); OutputStatusMessage(string.Format("Value: {0}", pair.Value)); } } OutputStatusMessage(string.Format("Id: {0}", adGroup.Id)); OutputStatusMessage(string.Format("Language: {0}", adGroup.Language)); OutputStatusMessage(string.Format("Name: {0}", adGroup.Name)); OutputStatusMessage(string.Format("NativeBidAdjustment: {0}", adGroup.NativeBidAdjustment)); OutputStatusMessage(string.Format("Network: {0}", adGroup.Network)); OutputStatusMessage(string.Format("PricingModel: {0}", adGroup.PricingModel)); OutputStatusMessage(string.Format("SearchBid: {0}", adGroup.SearchBid != null ? adGroup.SearchBid.Amount : 0)); if (adGroup.StartDate != null) { OutputStatusMessage(string.Format("StartDate: {0}/{1}/{2}", adGroup.StartDate.Month, adGroup.StartDate.Day, adGroup.StartDate.Year)); } OutputStatusMessage(string.Format("Status: {0}", adGroup.Status)); OutputStatusMessage(string.Format("TrackingUrlTemplate: {0}", adGroup.TrackingUrlTemplate)); OutputStatusMessage("UrlCustomParameters: "); if (adGroup.UrlCustomParameters != null && adGroup.UrlCustomParameters.Parameters != null) { foreach (var customParameter in adGroup.UrlCustomParameters.Parameters) { OutputStatusMessage(string.Format("\tKey: {0}", customParameter.Key)); OutputStatusMessage(string.Format("\tValue: {0}", customParameter.Value)); } } } }
public static AdGroup CreateAdGroup(int id) { AdGroup adGroup = new AdGroup(); adGroup.ID = id; return adGroup; }
/// <summary> /// Outputs the ad group identifiers, as well as any partial errors /// </summary> /// <param name="adGroups"></param> /// <param name="adGroupIds"></param> /// <param name="partialErrors"></param> protected void OutputAdGroupsWithPartialErrors( AdGroup[] adGroups, long?[] adGroupIds, IEnumerable<BatchError> partialErrors) { if (adGroupIds == null) { return; } // Output the identifier of each successfully added ad group. for (var index = 0; index < adGroupIds.Length; index++) { // The array of keyword identifiers equals the size of the attempted ad groups. If the element // is not null, the ad group at that index was added successfully and has an ad group identifer. if (adGroupIds[index] != null) { OutputStatusMessage(String.Format("AdGroup[{0}] (Name:{1}) successfully added and assigned AdGroupId {2}", index, adGroups[index].Name, adGroupIds[index])); } } // Output the error details for any ad group not successfully added. // Note also that multiple error reasons may exist for the same attempted ad group. foreach (BatchError error in partialErrors) { // The index of the partial errors is equal to the index of the list // specified in the call to AddAdGroups. OutputStatusMessage(String.Format("\nAdGroup[{0}] (Name:{1}) not added due to the following error:", error.Index, adGroups[error.Index].Name)); OutputStatusMessage(String.Format("\tIndex: {0}", error.Index)); OutputStatusMessage(String.Format("\tCode: {0}", error.Code)); OutputStatusMessage(String.Format("\tErrorCode: {0}", error.ErrorCode)); OutputStatusMessage(String.Format("\tMessage: {0}", error.Message)); // In the case of an EditorialError, more details are available if (error.Type == "EditorialError" && error.ErrorCode == "CampaignServiceEditorialValidationError") { OutputStatusMessage(String.Format("\tDisapprovedText: {0}", ((EditorialError)(error)).DisapprovedText)); OutputStatusMessage(String.Format("\tLocation: {0}", ((EditorialError)(error)).Location)); OutputStatusMessage(String.Format("\tPublisherCountry: {0}", ((EditorialError)(error)).PublisherCountry)); OutputStatusMessage(String.Format("\tReasonCode: {0}\n", ((EditorialError)(error)).ReasonCode)); } } OutputStatusMessage("\n"); }
public static AdGroupReturnValue CreateAdGroup(AdWordsUser user, AdGroupLo adGroupLo) { using (AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201710.AdGroupService)) { List <AdGroupOperation> operations = new List <AdGroupOperation>(); // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.name = adGroupLo.Name; adGroup.status = AdGroupStatus.PAUSED; adGroup.campaignId = adGroupLo.CampaignId; // Set the ad group bids. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); CpcBid cpcBid = new CpcBid(); cpcBid.bid = new Money(); cpcBid.bid.microAmount = 10000000; biddingConfig.bids = new Bids[] { cpcBid }; adGroup.biddingStrategyConfiguration = biddingConfig; // Optional: Set targeting restrictions. // Depending on the criterionTypeGroup value, most TargetingSettingDetail // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value // works for RLSA campaigns - Search campaigns targeting using a // remarketing list. TargetingSetting targetingSetting = new TargetingSetting(); // Restricting to serve ads that match your ad group placements. // This is equivalent to choosing "Target and bid" in the UI. TargetingSettingDetail placementDetail = new TargetingSettingDetail(); placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT; placementDetail.targetAll = false; // Using your ad group verticals only for bidding. This is equivalent // to choosing "Bid only" in the UI. TargetingSettingDetail verticalDetail = new TargetingSettingDetail(); verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL; verticalDetail.targetAll = true; targetingSetting.details = new TargetingSettingDetail[] { placementDetail, verticalDetail }; adGroup.settings = new Setting[] { targetingSetting }; // Set the rotation mode. AdGroupAdRotationMode rotationMode = new AdGroupAdRotationMode(); rotationMode.adRotationMode = AdRotationMode.OPTIMIZE; adGroup.adGroupAdRotationMode = rotationMode; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.ADD; operation.operand = adGroup; operations.Add(operation); AdGroupReturnValue returnDGroup; try { // Create the ad group. returnDGroup = adGroupService.mutate(operations.ToArray()); } catch (Exception e) { throw new System.ApplicationException("Failed to create ad group.", e); } return(returnDGroup); } }
protected override Core.Services.ServiceOutcome DoPipelineWork() { Dictionary <Consts.FileTypes, List <string> > filesByType = (Dictionary <Consts.FileTypes, List <string> >)Delivery.Parameters["FilesByType"]; StringBuilder warningsStr = new StringBuilder(); Dictionary <string, Campaign> campaignsData = new Dictionary <string, Campaign>(); Dictionary <string, AdGroup> adGroupsData = new Dictionary <string, AdGroup>(); Dictionary <string, Ad> ads = new Dictionary <string, Ad>(); Dictionary <string, List <Ad> > adsBycreatives = new Dictionary <string, List <Ad> >(); var adStatIds = new Dictionary <string, string>(); var insertedAds = new Dictionary <string, string>(); var storyIds = new Dictionary <string, Dictionary <string, string> >(); var photoIds = new Dictionary <string, Dictionary <string, string> >(); DeliveryOutput currentOutput = Delivery.Outputs.First(); currentOutput.Checksum = new Dictionary <string, double>(); using (this.ImportManager = new AdMetricsImportManager(this.Instance.InstanceID, new MetricsImportManagerOptions() { MeasureOptions = MeasureOptions.IsTarget | MeasureOptions.IsCalculated | MeasureOptions.IsBackOffice, MeasureOptionsOperator = OptionsOperator.Not, SegmentOptions = Data.Objects.SegmentOptions.All, SegmentOptionsOperator = OptionsOperator.And })) { this.ImportManager.BeginImport(this.Delivery); #region AdSets if (filesByType.ContainsKey(Consts.FileTypes.CampaignGroups)) { List <string> campaignsFiles = filesByType[Consts.FileTypes.CampaignGroups]; foreach (var campaignFile in campaignsFiles) { DeliveryFile campaigns = this.Delivery.Files[campaignFile]; var campaignsReader = new JsonDynamicReader(campaigns.OpenContents(), "$.data[*].*"); using (campaignsReader) { while (campaignsReader.Read()) { Campaign camp = new Campaign() { Name = campaignsReader.Current.name, OriginalID = Convert.ToString(campaignsReader.Current.id), }; campaignsData.Add(camp.OriginalID, camp); } } } } #endregion #region AdGroups if (filesByType.ContainsKey(Consts.FileTypes.AdSets)) { List <string> adSetList = filesByType[Consts.FileTypes.AdSets]; foreach (var adSet in adSetList) { DeliveryFile adSetDF = this.Delivery.Files[adSet]; var adSetReader = new JsonDynamicReader(adSetDF.OpenContents(), "$.data[*].*"); using (adSetReader) { while (adSetReader.Read()) { var adGroupObj = new AdGroup() { Value = adSetReader.Current.name, OriginalID = Convert.ToString(adSetReader.Current.id), }; if (campaignsData.ContainsKey(adSetReader.Current.campaign_group_id)) { adGroupObj.Campaign = campaignsData[adSetReader.Current.campaign_group_id]; } adGroupsData.Add(adGroupObj.OriginalID, adGroupObj); } } } } #endregion #region adGroups And Targeting //****************************************************************************************************************************************************** if (filesByType.ContainsKey(Consts.FileTypes.AdGroups)) { List <string> adGroupsFiles = filesByType[Consts.FileTypes.AdGroups]; foreach (var adGroup in adGroupsFiles) { #region foreach DeliveryFile adGroups = this.Delivery.Files[adGroup]; var adGroupsReader = new JsonDynamicReader(FileManager.Open(adGroups.Location), "$.data[*].*"); using (adGroupsReader) { while (adGroupsReader.Read()) { var campaignId = Convert.ToString(adGroupsReader.Current.campaign_id); if (adGroupsData.ContainsKey(campaignId) && ((AdGroup)adGroupsData[campaignId]).Campaign != null) { Ad ad = new Ad(); ad.OriginalID = Convert.ToString(adGroupsReader.Current.id); ad.Segments = new Dictionary <Segment, SegmentObject>(); ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.Campaign]] = ((AdGroup)adGroupsData[Convert.ToString(adGroupsReader.Current.campaign_id)]).Campaign; ad.Name = adGroupsReader.Current.name; ad.Channel = new Channel() { ID = 6 }; ad.Account = new Account() { ID = this.Delivery.Account.ID, OriginalID = this.Delivery.Account.OriginalID.ToString() }; if (adGroupsData.ContainsKey(adGroupsReader.Current.campaign_id)) { ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.AdGroup]] = adGroupsData[adGroupsReader.Current.campaign_id]; } // adgroup targeting string age_min = string.Empty; if (((Dictionary <string, object>)adGroupsReader.Current.targeting).ContainsKey("age_min")) { age_min = adGroupsReader.Current.targeting["age_min"]; } if (!string.IsNullOrEmpty(age_min)) { AgeTarget ageTarget = new AgeTarget() { FromAge = int.Parse(age_min), ToAge = int.Parse(adGroupsReader.Current.targeting["age_max"]) }; ad.Targets.Add(ageTarget); } List <object> genders = null; if (((Dictionary <string, object>)adGroupsReader.Current.targeting).ContainsKey("genders")) { genders = adGroupsReader.Current.targeting["genders"]; } if (genders != null) { foreach (object gender in genders) { GenderTarget genderTarget = new GenderTarget(); if (gender.ToString() == "1") { genderTarget.Gender = Gender.Male; } else if (gender.ToString() == "2") { genderTarget.Gender = Gender.Female; } else { genderTarget.Gender = Gender.Unspecified; } genderTarget.OriginalID = gender.ToString(); ad.Targets.Add(genderTarget); } } if (adGroupsReader.Current.creative_ids != null) { foreach (string creative in adGroupsReader.Current.creative_ids) { if (!adsBycreatives.ContainsKey(creative)) { adsBycreatives.Add(creative, new List <Ad>()); } adsBycreatives[creative].Add(ad); } } ads.Add(ad.OriginalID, ad); } } } #endregion } } //****************************************************************************************************************************************************** #endregion adGroups And Targeting //GetAdGroupStats #region for validation foreach (var measure in this.ImportManager.Measures) { if (measure.Value.Options.HasFlag(MeasureOptions.ValidationRequired)) { if (!currentOutput.Checksum.ContainsKey(measure.Key)) { currentOutput.Checksum.Add(measure.Key, 0); //TODO : SHOULD BE NULL BUT SINCE CAN'T ADD NULLABLE ...TEMP } } } //************************************************************************** #endregion Dictionary <string, List <Dictionary <string, object> > > conversion_data = new Dictionary <string, List <Dictionary <string, object> > >(); if (filesByType.ContainsKey(Consts.FileTypes.ConversionsStats)) { #region Conversions List <string> conversionFiles = filesByType[Consts.FileTypes.ConversionsStats]; foreach (string conversionFile in conversionFiles) { DeliveryFile creativeFile = Delivery.Files[conversionFile]; var conversionCreativesReader = new JsonDynamicReader(creativeFile.OpenContents(), "$.data[*].*"); using (conversionCreativesReader) { this.Mappings.OnFieldRequired = field => conversionCreativesReader.Current[field]; while (conversionCreativesReader.Read()) { if (((Edge.Data.Pipeline.DynamicDictionaryObject)(conversionCreativesReader.Current)).Values == null) { break; // in case of empty data (e.g. data [] ) } if (!conversion_data.ContainsKey(conversionCreativesReader.Current.adgroup_id)) { Dictionary <string, string> adConversionData = new Dictionary <string, string>(); //string TotalConversionsManyPerClick, Leads, Signups, Purchases; List <object> actions = conversionCreativesReader.Current.actions; if (actions.Count > 0) { List <Dictionary <string, object> > action_list = actions.Select(s => (Dictionary <string, object>)s).ToList(); List <Dictionary <string, object> > action_items = action_list.Where(dict => dict.ContainsKey("action_type") && dict.ContainsKey("value") && ( dict["action_type"].ToString().Equals("offsite_conversion") || dict["action_type"].ToString().Equals("offsite_conversion.lead") || dict["action_type"].ToString().Equals("offsite_conversion.registration") || dict["action_type"].ToString().Equals("offsite_conversion.add_to_cart") || dict["action_type"].ToString().Equals("offsite_conversion.checkout") || dict["action_type"].ToString().Equals("offsite_conversion.key_page_view") || dict["action_type"].ToString().Equals("offsite_conversion.other") ) ).ToList(); if (action_items.Count > 0) { conversion_data.Add(conversionCreativesReader.Current.adgroup_id, action_items); } } } } //End of While read } // End of Using reader } //End Foreach conversion file #endregion } //End if contains conversion file #region AdGroupStats start new import session List <string> adGroupStatsFiles = filesByType[Consts.FileTypes.AdGroupStats]; foreach (var adGroupStat in adGroupStatsFiles) { DeliveryFile adGroupStats = this.Delivery.Files[adGroupStat]; var adGroupStatsReader = new JsonDynamicReader(adGroupStats.OpenContents(), "$.data[*].*"); using (adGroupStatsReader) { while (adGroupStatsReader.Read()) { #region Create Metrics AdMetricsUnit adMetricsUnit = new AdMetricsUnit(); adMetricsUnit.Output = currentOutput; adMetricsUnit.MeasureValues = new Dictionary <Measure, double>(); Ad tempAd; try { var x = adGroupStatsReader.Current.adgroup_id; } catch (Exception) { continue; } if (adGroupStatsReader.Current.adgroup_id != null) { adStatIds[adGroupStatsReader.Current.adgroup_id] = adGroupStatsReader.Current.adgroup_id; if (ads.TryGetValue(adGroupStatsReader.Current.adgroup_id, out tempAd)) { adMetricsUnit.Ad = tempAd; //adMetricsUnit.PeriodStart = this.Delivery.TimePeriodDefinition.Start.ToDateTime(); //adMetricsUnit.PeriodEnd = this.Delivery.TimePeriodDefinition.End.ToDateTime(); // Common and Facebook specific meausures /* Sets totals for validations */ if (currentOutput.Checksum.ContainsKey(Measure.Common.Clicks)) { currentOutput.Checksum[Measure.Common.Clicks] += Convert.ToDouble(adGroupStatsReader.Current.clicks); } if (currentOutput.Checksum.ContainsKey(Measure.Common.Impressions)) { currentOutput.Checksum[Measure.Common.Impressions] += Convert.ToDouble(adGroupStatsReader.Current.impressions); } if (currentOutput.Checksum.ContainsKey(Measure.Common.Cost)) { currentOutput.Checksum[Measure.Common.Cost] += Convert.ToDouble(adGroupStatsReader.Current.spent) / 100d; } /* Sets measures values */ adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Clicks], Convert.ToInt64(adGroupStatsReader.Current.clicks)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.UniqueClicks], Convert.ToInt64(adGroupStatsReader.Current.unique_clicks)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Impressions], Convert.ToInt64(adGroupStatsReader.Current.impressions)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.UniqueImpressions], Convert.ToInt64(adGroupStatsReader.Current.unique_impressions)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[Measure.Common.Cost], Convert.ToDouble(Convert.ToDouble(adGroupStatsReader.Current.spent) / 100d)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.SocialImpressions], double.Parse(adGroupStatsReader.Current.social_impressions)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.SocialUniqueImpressions], double.Parse(adGroupStatsReader.Current.social_unique_impressions)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.SocialClicks], double.Parse(adGroupStatsReader.Current.social_clicks)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.SocialUniqueClicks], double.Parse(adGroupStatsReader.Current.social_unique_clicks)); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.SocialCost], Convert.ToDouble(adGroupStatsReader.Current.social_spent) / 100d); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.Actions], 0); //adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.Connections], double.Parse(adGroupStatsReader.Current.connections)); //Setting conversions from conversion files data List <Dictionary <string, object> > adgroup_conversion_data; if (conversion_data.TryGetValue(adGroupStatsReader.Current.adgroup_id, out adgroup_conversion_data)) { var TotalConversionsManyPerClick = from element in adgroup_conversion_data where element["action_type"].Equals("offsite_conversion") select element["value"]; var Leads = from element in adgroup_conversion_data where element["action_type"].Equals("offsite_conversion.lead") select element["value"]; var Signups = from element in adgroup_conversion_data where element["action_type"].Equals("offsite_conversion.registration") select element["value"]; //TO DO : Get field from Configuration var Purchases = from element in adgroup_conversion_data where element["action_type"].Equals(this.Delivery.Parameters["API_Purchases_Field_Name"]) select element["value"]; //add values to metrics unit adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.TotalConversionsManyPerClick], Convert.ToDouble(TotalConversionsManyPerClick.DefaultIfEmpty("0").FirstOrDefault())); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.Leads], Convert.ToDouble(Leads.DefaultIfEmpty("0").FirstOrDefault())); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.Signups], Convert.ToDouble(Signups.DefaultIfEmpty("0").FirstOrDefault())); adMetricsUnit.MeasureValues.Add(this.ImportManager.Measures[MeasureNames.Purchases], Convert.ToDouble(Purchases.DefaultIfEmpty("0").FirstOrDefault())); } this.ImportManager.ImportMetrics(adMetricsUnit); } else { warningsStr.AppendLine(string.Format("Ad {0} does not exist in the stats report delivery id: {1}", adGroupStatsReader.Current.id, this.Delivery.DeliveryID)); } } else { warningsStr.AppendLine("adGroupStatsReader.Current.id=null"); } #endregion } } } #endregion AdGroupStats start new import session #region Creatives List <string> creativeFiles = filesByType[Consts.FileTypes.Creatives]; Dictionary <string, string> usedCreatives = new Dictionary <string, string>(); foreach (string creative in creativeFiles) { DeliveryFile creativeFile = Delivery.Files[creative]; var adGroupCreativesReader = new JsonDynamicReader(creativeFile.OpenContents(), "$.data[*].*"); using (adGroupCreativesReader) { //this.Mappings.OnFieldRequired = field => if((field == "object_url" && adGroupCreativesReader.Current[field] != null) || field != "object_url")adGroupCreativesReader.Current[field]; this.Mappings.OnFieldRequired = field => adGroupCreativesReader.Current[field]; while (adGroupCreativesReader.Read()) { List <Ad> adsByCreativeID = null; if (adsBycreatives.ContainsKey(adGroupCreativesReader.Current.id)) { if (!usedCreatives.ContainsKey(adGroupCreativesReader.Current.id)) { usedCreatives.Add(adGroupCreativesReader.Current.id, adGroupCreativesReader.Current.id); adsByCreativeID = adsBycreatives[adGroupCreativesReader.Current.id]; } } if (adsByCreativeID != null) { foreach (Ad ad in adsByCreativeID) { if (!adStatIds.ContainsKey(ad.OriginalID)) { continue; } ad.Creatives = new List <Creative>(); if (!string.IsNullOrEmpty(adGroupCreativesReader.Current.object_type)) { string objectType = adGroupCreativesReader.Current.object_type; switch (objectType.ToUpper()) { case "SHARE": { #region Ads Type SHARE if (!string.IsNullOrEmpty(adGroupCreativesReader.Current.object_story_id)) { Dictionary <string, string> shareCreativeData; string object_story_id = adGroupCreativesReader.Current.object_story_id; if (storyIds.ContainsKey(object_story_id)) { shareCreativeData = storyIds[object_story_id]; } else { var accessToken = this.Instance.Configuration.Options[FacebookConfigurationOptions.Auth_AccessToken]; shareCreativeData = GetShareCreativeData(object_story_id, accessToken); } ad.DestinationUrl = shareCreativeData["link"]; if (this.Mappings != null && this.Mappings.Objects.ContainsKey(typeof(Ad))) { this.Mappings.Objects[typeof(Ad)].Apply(ad); var trackersReadCommands = from n in this.Mappings.Objects[typeof(Ad)].ReadCommands where n.Field.Equals("link_url") select n; foreach (var command in trackersReadCommands) { string trackerValue = ApplyRegex(ad.DestinationUrl, command.RegexPattern); if (!String.IsNullOrEmpty(trackerValue)) { ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.Tracker]].Value = trackerValue; ad.Segments[this.ImportManager.SegmentTypes[Segment.Common.Tracker]].OriginalID = trackerValue; } } } ad.Creatives.Add(GetTextCreative(shareCreativeData["text"], adGroupCreativesReader)); ad.Creatives.Add(GetBodyCreative(shareCreativeData["description"], adGroupCreativesReader)); ad.Creatives.Add(GetImageCreative(shareCreativeData["picture"], adGroupCreativesReader)); } #endregion break; } case "DOMAIN": { #region Ads Type DOMAIN if (!string.IsNullOrEmpty(adGroupCreativesReader.Current.object_url)) { if (Instance.Configuration.Options.ContainsKey(FacebookConfigurationOptions.AdGroupCreativeFields)) { ad.DestinationUrl = adGroupCreativesReader.Current.object_url; } } else if (!string.IsNullOrEmpty(adGroupCreativesReader.Current.link_url)) { ad.DestinationUrl = adGroupCreativesReader.Current.link_url; } else { ad.DestinationUrl = "UnKnown Url"; } /*Get Data from Mapping E.g Tracker*/ if (this.Mappings != null && this.Mappings.Objects.ContainsKey(typeof(Ad))) { this.Mappings.Objects[typeof(Ad)].Apply(ad); } if (adGroupCreativesReader.Current.image_url != null) { CreateImageCreatives(ad, adGroupCreativesReader); } ad.Creatives.Add(GetTextCreative(adGroupCreativesReader)); ad.Creatives.Add(GetBodyCreative(adGroupCreativesReader)); #endregion break; } default: { #region Ads Type not handeled string adtype = objectType.ToUpper(); ad.DestinationUrl = adtype + " Ad Type"; /*Get Data from Mapping E.g Tracker*/ if (this.Mappings != null && this.Mappings.Objects.ContainsKey(typeof(Ad))) { this.Mappings.Objects[typeof(Ad)].Apply(ad); } TextCreative unhandeledTextAd_title = new TextCreative() { OriginalID = ad.OriginalID, TextType = TextCreativeType.Title, Text = adtype + " Ad Type" }; ad.Creatives.Add(unhandeledTextAd_title); #endregion break; } } if (!insertedAds.ContainsKey(ad.OriginalID)) { insertedAds[ad.OriginalID] = ad.OriginalID; this.ImportManager.ImportAd(ad); } } } } //TODO: REPORT PROGRESS 2 ReportProgress(PROGRESS) } } #endregion } // End foreach creative currentOutput.Status = DeliveryOutputStatus.Imported; this.ImportManager.EndImport(); if (!string.IsNullOrEmpty(warningsStr.ToString())) { Log.Write(warningsStr.ToString(), LogMessageType.Warning); } } return(Core.Services.ServiceOutcome.Success); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to which ad groups are /// added.</param> public void Run(AdWordsUser user, long campaignId) { using (AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201710.AdGroupService)) { List <AdGroupOperation> operations = new List <AdGroupOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.name = string.Format("Earth to Mars Cruises #{0}", ExampleUtilities.GetRandomString()); adGroup.status = AdGroupStatus.ENABLED; adGroup.campaignId = campaignId; // Set the ad group bids. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); CpcBid cpcBid = new CpcBid(); cpcBid.bid = new Money(); cpcBid.bid.microAmount = 10000000; biddingConfig.bids = new Bids[] { cpcBid }; adGroup.biddingStrategyConfiguration = biddingConfig; // Optional: Set targeting restrictions. // Depending on the criterionTypeGroup value, most TargetingSettingDetail // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value // works for RLSA campaigns - Search campaigns targeting using a // remarketing list. TargetingSetting targetingSetting = new TargetingSetting(); // Restricting to serve ads that match your ad group placements. // This is equivalent to choosing "Target and bid" in the UI. TargetingSettingDetail placementDetail = new TargetingSettingDetail(); placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT; placementDetail.targetAll = false; // Using your ad group verticals only for bidding. This is equivalent // to choosing "Bid only" in the UI. TargetingSettingDetail verticalDetail = new TargetingSettingDetail(); verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL; verticalDetail.targetAll = true; targetingSetting.details = new TargetingSettingDetail[] { placementDetail, verticalDetail }; adGroup.settings = new Setting[] { targetingSetting }; // Set the rotation mode. AdGroupAdRotationMode rotationMode = new AdGroupAdRotationMode(); rotationMode.adRotationMode = AdRotationMode.OPTIMIZE; adGroup.adGroupAdRotationMode = rotationMode; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.ADD; operation.operand = adGroup; operations.Add(operation); } try { // Create the ad group. AdGroupReturnValue retVal = adGroupService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (AdGroup newAdGroup in retVal.value) { Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.", newAdGroup.id, newAdGroup.name); } } else { Console.WriteLine("No ad groups were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create ad groups.", e); } } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { Service = new ServiceClient<ICampaignManagementService>(authorizationData); // Specify one or more campaigns. var campaign = new Campaign { Name = "Women's Shoes" + DateTime.UtcNow, Description = "Red shoes line.", BudgetType = BudgetLimitType.MonthlyBudgetSpendUntilDepleted, MonthlyBudget = 1000.00, TimeZone = "PacificTimeUSCanadaTijuana", DaylightSaving = true }; // Specify one or more ad groups. var adGroup = new AdGroup { Name = "Women's Red Shoe Sale", AdDistribution = AdDistribution.Search, BiddingModel = BiddingModel.Keyword, PricingModel = PricingModel.Cpc, StartDate = null, EndDate = new Date { Month = 12, Day = 31, Year = 2015 }, ExactMatchBid = new Bid { Amount = 0.09 }, PhraseMatchBid = new Bid { Amount = 0.07 }, Language = "English" }; // In this example only the second keyword should succeed. The Text of the first keyword exceeds the limit, // and the third keyword is a duplicate of the second keyword. var keywords = new[] { new Keyword { Bid = new Bid { Amount = 0.47 }, Param2 = "10% Off", MatchType = MatchType.Broad, Text = "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes " + "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes " + "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes" }, new Keyword { Bid = new Bid { Amount = 0.47 }, Param2 = "10% Off", MatchType = MatchType.Phrase, Text = "Brand-A Shoes" }, new Keyword { Bid = new Bid { Amount = 0.47 }, Param2 = "10% Off", MatchType = MatchType.Phrase, Text = "Brand-A Shoes" } }; // In this example only the second ad should succeed. The Title of the first ad is empty and not valid, // and the third ad is a duplicate of the second ad. var ads = new Ad[] { new TextAd { DestinationUrl = "http://www.contoso.com/womenshoesale", DisplayUrl = "Contoso.com", Text = "Huge Savings on red shoes.", Title = "" }, new TextAd { DestinationUrl = "http://www.contoso.com/womenshoesale", DisplayUrl = "Contoso.com", Text = "Huge Savings on red shoes.", Title = "Women's Shoe Sale" }, new TextAd { DestinationUrl = "http://www.contoso.com/womenshoesale", DisplayUrl = "Contoso.com", Text = "Huge Savings on red shoes.", Title = "Women's Shoe Sale" } }; // Add the campaign, ad group, keywords, and ads var campaignIds = (long[]) await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign }); var adGroupIds = (long[])await AddAdGroupsAsync(campaignIds[0], new[] { adGroup }); AddKeywordsResponse addKeywordsResponse = await AddKeywordsAsync(adGroupIds[0], keywords); long?[] keywordIds = addKeywordsResponse.KeywordIds.ToArray(); BatchError[] keywordErrors = addKeywordsResponse.PartialErrors.ToArray(); AddAdsResponse addAdsResponse = await AddAdsAsync(adGroupIds[0], ads); long?[] adIds = addAdsResponse.AdIds.ToArray(); BatchError[] adErrors = addAdsResponse.PartialErrors.ToArray(); // Print the new assigned campaign and ad group identifiers PrintCampaignIdentifiers(campaignIds); PrintAdGroupIdentifiers(adGroupIds); // Print the new assigned keyword and ad identifiers, as well as any partial errors PrintKeywordResults(keywords, keywordIds, keywordErrors); PrintAdResults(ads, adIds, adErrors); // Delete the campaign, ad group, keyword, and ad that were previously added. // You should remove this line 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])); } // 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); } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { Service = new ServiceClient <ICampaignManagementService>(authorizationData); // Specify one or more campaigns. var campaign = new Campaign { Name = "Women's Shoes" + DateTime.UtcNow, Description = "Red shoes line.", BudgetType = BudgetLimitType.MonthlyBudgetSpendUntilDepleted, MonthlyBudget = 1000.00, TimeZone = "PacificTimeUSCanadaTijuana", DaylightSaving = true }; // Specify one or more ad groups. var adGroup = new AdGroup { Name = "Women's Red Shoe Sale", AdDistribution = AdDistribution.Search, BiddingModel = BiddingModel.Keyword, PricingModel = PricingModel.Cpc, StartDate = null, EndDate = new Date { Month = 12, Day = 31, Year = 2015 }, ExactMatchBid = new Bid { Amount = 0.09 }, PhraseMatchBid = new Bid { Amount = 0.07 }, Language = "English" }; // In this example only the second keyword should succeed. The Text of the first keyword exceeds the limit, // and the third keyword is a duplicate of the second keyword. var keywords = new[] { new Keyword { Bid = new Bid { Amount = 0.47 }, Param2 = "10% Off", MatchType = MatchType.Broad, Text = "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes " + "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes " + "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes" }, new Keyword { Bid = new Bid { Amount = 0.47 }, Param2 = "10% Off", MatchType = MatchType.Phrase, Text = "Brand-A Shoes" }, new Keyword { Bid = new Bid { Amount = 0.47 }, Param2 = "10% Off", MatchType = MatchType.Phrase, Text = "Brand-A Shoes" } }; // In this example only the second ad should succeed. The Title of the first ad is empty and not valid, // and the third ad is a duplicate of the second ad. var ads = new Ad[] { new TextAd { DestinationUrl = "http://www.contoso.com/womenshoesale", DisplayUrl = "Contoso.com", Text = "Huge Savings on red shoes.", Title = "" }, new TextAd { DestinationUrl = "http://www.contoso.com/womenshoesale", DisplayUrl = "Contoso.com", Text = "Huge Savings on red shoes.", Title = "Women's Shoe Sale" }, new TextAd { DestinationUrl = "http://www.contoso.com/womenshoesale", DisplayUrl = "Contoso.com", Text = "Huge Savings on red shoes.", Title = "Women's Shoe Sale" } }; // Add the campaign, ad group, keywords, and ads var campaignIds = (long[]) await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign }); var adGroupIds = (long[]) await AddAdGroupsAsync(campaignIds[0], new[] { adGroup }); AddKeywordsResponse addKeywordsResponse = await AddKeywordsAsync(adGroupIds[0], keywords); long?[] keywordIds = addKeywordsResponse.KeywordIds.ToArray(); BatchError[] keywordErrors = addKeywordsResponse.PartialErrors.ToArray(); AddAdsResponse addAdsResponse = await AddAdsAsync(adGroupIds[0], ads); long?[] adIds = addAdsResponse.AdIds.ToArray(); BatchError[] adErrors = addAdsResponse.PartialErrors.ToArray(); // Print the new assigned campaign and ad group identifiers PrintCampaignIdentifiers(campaignIds); PrintAdGroupIdentifiers(adGroupIds); // Print the new assigned keyword and ad identifiers, as well as any partial errors PrintKeywordResults(keywords, keywordIds, keywordErrors); PrintAdResults(ads, adIds, adErrors); // Delete the campaign, ad group, keyword, and ad that were previously added. // You should remove this line 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])); } // 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">Id of the campaign to which ad groups are /// added.</param> public void Run(AdWordsUser user, long campaignId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService) user.GetService(AdWordsService.v201509.AdGroupService); List<AdGroupOperation> operations = new List<AdGroupOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.name = string.Format("Earth to Mars Cruises #{0}", ExampleUtilities.GetRandomString()); adGroup.status = AdGroupStatus.ENABLED; adGroup.campaignId = campaignId; // Set the ad group bids. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); CpcBid cpcBid = new CpcBid(); cpcBid.bid = new Money(); cpcBid.bid.microAmount = 10000000; biddingConfig.bids = new Bids[] {cpcBid}; adGroup.biddingStrategyConfiguration = biddingConfig; // Optional: Set targeting restrictions. // Depending on the criterionTypeGroup value, most TargetingSettingDetail // only affect Display campaigns. However, the USER_INTEREST_AND_LIST value // works for RLSA campaigns - Search campaigns targeting using a // remarketing list. TargetingSetting targetingSetting = new TargetingSetting(); // Restricting to serve ads that match your ad group placements. // This is equivalent to choosing "Target and bid" in the UI. TargetingSettingDetail placementDetail = new TargetingSettingDetail(); placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT; placementDetail.targetAll = false; // Using your ad group verticals only for bidding. This is equivalent // to choosing "Bid only" in the UI. TargetingSettingDetail verticalDetail = new TargetingSettingDetail(); verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL; verticalDetail.targetAll = true; targetingSetting.details = new TargetingSettingDetail[] {placementDetail, verticalDetail}; adGroup.settings = new Setting[] {targetingSetting}; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.ADD; operation.operand = adGroup; operations.Add(operation); } try { // Create the ad group. AdGroupReturnValue retVal = adGroupService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (AdGroup newAdGroup in retVal.value) { Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.", newAdGroup.id, newAdGroup.name); } } else { Console.WriteLine("No ad groups were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create ad groups.", e); } }
/// <summary> /// Получает список членов группы AD /// </summary> /// <param name="adGroup">группа AD</param> /// <returns></returns> public static List<KeyValuePair<string, string>> GetUserListByAdGroup(AdGroup adGroup) { Uri uri = new Uri($"{OdataServiceUri}/Ad/GetUserListByAdGroup?group={adGroup}"); string jsonString = GetJson(uri); var sidNamePairs = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(jsonString); return sidNamePairs; }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="campaignId">Id of the campaign to which ad groups are /// added.</param> public void Run(AdWordsUser user, long campaignId) { // Get the AdGroupService. AdGroupService adGroupService = (AdGroupService)user.GetService(AdWordsService.v201402.AdGroupService); List <AdGroupOperation> operations = new List <AdGroupOperation>(); for (int i = 0; i < NUM_ITEMS; i++) { // Create the ad group. AdGroup adGroup = new AdGroup(); adGroup.name = string.Format("Earth to Mars Cruises #{0}", ExampleUtilities.GetRandomString()); adGroup.status = AdGroupStatus.ENABLED; adGroup.campaignId = campaignId; // Set the ad group bids. BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration(); CpmBid cpmBid = new CpmBid(); cpmBid.bid = new Money(); cpmBid.bid.microAmount = 10000000; biddingConfig.bids = new Bids[] { cpmBid }; adGroup.biddingStrategyConfiguration = biddingConfig; // Optional: Set targeting restrictions. // These setting only affect serving for the Display Network. TargetingSetting targetingSetting = new TargetingSetting(); TargetingSettingDetail placementDetail = new TargetingSettingDetail(); placementDetail.criterionTypeGroup = CriterionTypeGroup.PLACEMENT; placementDetail.targetAll = true; TargetingSettingDetail verticalDetail = new TargetingSettingDetail(); verticalDetail.criterionTypeGroup = CriterionTypeGroup.VERTICAL; verticalDetail.targetAll = false; targetingSetting.details = new TargetingSettingDetail[] { placementDetail, verticalDetail }; adGroup.settings = new Setting[] { targetingSetting }; // Create the operation. AdGroupOperation operation = new AdGroupOperation(); operation.@operator = Operator.ADD; operation.operand = adGroup; operations.Add(operation); } try { // Create the ad group. AdGroupReturnValue retVal = adGroupService.mutate(operations.ToArray()); // Display the results. if (retVal != null && retVal.value != null && retVal.value.Length > 0) { foreach (AdGroup newAdGroup in retVal.value) { Console.WriteLine("Ad group with id = '{0}' and name = '{1}' was created.", newAdGroup.id, newAdGroup.name); } } else { Console.WriteLine("No ad groups were created."); } } catch (Exception ex) { throw new System.ApplicationException("Failed to create ad groups.", 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="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="omitUnselectedResourceNames">Specifies whether to omit unselected resource /// names from response.</param> public void Run(GoogleAdsClient client, long customerId, bool?omitUnselectedResourceNames) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V10.GoogleAdsService); try { string query = $@"SELECT ad_group.id, ad_group.status, ad_group_criterion.criterion_id, ad_group_criterion.keyword.text, ad_group_criterion.keyword.match_type FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group.status = 'ENABLED' AND ad_group_criterion.status IN ('ENABLED', 'PAUSED')"; // Adds omit_unselected_resource_names=true to the PARAMETERS clause of the // Google Ads Query Language (GAQL) query, which excludes the resource names of // all resources that aren't explicitly requested in the SELECT clause. // Enabling this option reduces payload size, but if you plan to use a returned // object in subsequent mutate operations, make sure you explicitly request its // "resource_name" field in the SELECT clause. // // Read more about PARAMETERS: // https://developers.google.com/google-ads/api/docs/query/structure#parameters if (omitUnselectedResourceNames.HasValue && omitUnselectedResourceNames.Value) { query += " PARAMETERS omit_unselected_resource_names=true"; } googleAdsService.SearchStream(customerId.ToString(), query, delegate(SearchGoogleAdsStreamResponse resp) { foreach (GoogleAdsRow criterionRow in resp.Results) { AdGroup adGroup = criterionRow.AdGroup; AdGroupCriterion criterion = criterionRow.AdGroupCriterion; string andResourceName = null; if (omitUnselectedResourceNames.HasValue && omitUnselectedResourceNames.Value) { andResourceName = ""; } else { andResourceName = $" and resource name '{adGroup.ResourceName}'"; } Console.WriteLine("Keyword with text '{0}', id = '{1}' and " + "match type = '{2}' was retrieved for ad group '{3}'{4}.", criterion.Keyword.Text, criterion.CriterionId, criterion.Keyword.MatchType, adGroup.Id, andResourceName); } } ); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
public async override Task RunAsync(AuthorizationData authorizationData) { try { Service = new ServiceClient<ICampaignManagementService>(authorizationData); // Specify a campaign. var campaign = new Campaign { Name = "Women's Shoes" + DateTime.UtcNow, Description = "Red shoes line.", BudgetType = BudgetLimitType.MonthlyBudgetSpendUntilDepleted, MonthlyBudget = 1000.00, TimeZone = "PacificTimeUSCanadaTijuana", DaylightSaving = true }; // Specify an ad group. var adGroup = new AdGroup { Name = "Women's Red Shoe Sale", AdDistribution = AdDistribution.Search, BiddingModel = BiddingModel.Keyword, PricingModel = PricingModel.Cpc, StartDate = null, EndDate = new Date { Month = 12, Day = 31, Year = 2015 }, ExactMatchBid = new Bid { Amount = 0.09 }, PhraseMatchBid = new Bid { Amount = 0.07 }, Language = "English" }; // Add the campaign and ad group var campaignIds = (long[])await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign }); var adGroupIds = (long[])await AddAdGroupsAsync(campaignIds[0], new[] { adGroup }); // Print the new assigned campaign and ad group identifiers PrintCampaignIdentifiers(campaignIds); PrintAdGroupIdentifiers(adGroupIds); // Bing Ads API Version 9 supports both Target and Target2 objects. You should use Target2. // This example compares Target and Target2, and demonstrates the impact of updating the // DayTimeTarget, IntentOption, and RadiusTarget2 nested in a Target2 object. var campaignTarget = new Target { Name = "My Campaign Target", DeviceOS = new DeviceOSTarget { Bids = new[] { new DeviceOSTargetBid { BidAdjustment = 10, DeviceName = "Smartphones", }, }, }, Day = new DayTarget { Bids = new[] { new DayTargetBid { BidAdjustment = 10, Day = Day.Friday } } }, Hour = new HourTarget { Bids = new[] { new HourTargetBid { BidAdjustment = 10, Hour = HourRange.ElevenAMToTwoPM } } }, Location = new LocationTarget { HasPhysicalIntent = true, MetroAreaTarget = new MetroAreaTarget { Bids = new List<MetroAreaTargetBid> { new MetroAreaTargetBid { BidAdjustment = 15, MetroArea = "Seattle-Tacoma, WA, WA US", IsExcluded = false } } }, RadiusTarget = new RadiusTarget { Bids = new[] { new RadiusTargetBid { BidAdjustment = 50, LatitudeDegrees = 47.755367, LongitudeDegrees = -122.091827, Radius = 5 } } } } }; var adGroupTarget = new Target { Name = "My Ad Group Target", Hour = new HourTarget { Bids = new[] { new HourTargetBid { BidAdjustment = 10, Hour = HourRange.SixPMToElevenPM } } } }; // Each customer has a target library that can be used to set up targeting for any campaign // or ad group within the specified customer. // Add a target to the library and associate it with the campaign. var campaignTargetId = (await AddTargetsToLibraryAsync(new[] { campaignTarget }))[0]; OutputStatusMessage(String.Format("Added Target Id: {0}\n", campaignTargetId)); SetTargetToCampaignAsync(campaignIds[0], campaignTargetId); OutputStatusMessage(String.Format("Associated CampaignId {0} with TargetId {1}.\n", campaignIds[0], campaignTargetId)); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get Campaign Target: \n"); var targets = await GetTargetsByIdsAsync(new[] { campaignTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get Campaign Target2: \n"); var targets2 = await GetTargetsByIds2Async(new[] { campaignTargetId }); PrintTarget2(targets2[0]); // Add a target to the library and associate it with the ad group. var adGroupTargetId = (await AddTargetsToLibraryAsync(new[] { adGroupTarget }))[0]; OutputStatusMessage(String.Format("Added Target Id: {0}\n", adGroupTargetId)); SetTargetToAdGroupAsync(adGroupIds[0], adGroupTargetId); OutputStatusMessage(String.Format("Associated AdGroupId {0} with TargetId {1}.\n", adGroupIds[0], adGroupTargetId)); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get AdGroup Target: \n"); targets = await GetTargetsByIdsAsync(new[] { adGroupTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get AdGroup Target2: \n"); targets2 = await GetTargetsByIds2Async(new[] { adGroupTargetId }); PrintTarget2(targets2[0]); // Update the ad group's target as a Target2 object with additional target types. // Existing target types such as DayTime, Location, and Radius must be specified // or they will not be included in the updated target. var target2 = new Target2 { Id = adGroupTargetId, Name = "My Target2", Age = new AgeTarget { Bids = new[] { new AgeTargetBid { BidAdjustment = 10, Age = AgeRange.EighteenToTwentyFive } } }, DayTime = new DayTimeTarget { Bids = new[] { new DayTimeTargetBid { BidAdjustment = 10, Day = Day.Friday, FromHour = 1, ToHour = 12, FromMinute = Minute.Zero, ToMinute = Minute.FortyFive } } }, DeviceOS = new DeviceOSTarget { Bids = new[] { new DeviceOSTargetBid { BidAdjustment = 20, DeviceName = "Tablets", }, }, }, Gender = new GenderTarget { Bids = new[] { new GenderTargetBid { BidAdjustment = 10, Gender = GenderType.Female } } }, Location = new LocationTarget2 { IntentOption = IntentOption.PeopleSearchingForOrViewingPages, CountryTarget = new CountryTarget { Bids = new[] { new CountryTargetBid { BidAdjustment = 10, CountryAndRegion = "US", IsExcluded = false } } }, MetroAreaTarget = new MetroAreaTarget { Bids = new List<MetroAreaTargetBid> { new MetroAreaTargetBid { BidAdjustment = 15, MetroArea = "Seattle-Tacoma, WA, WA US", IsExcluded = false } } }, PostalCodeTarget = new PostalCodeTarget { Bids = new[] { new PostalCodeTargetBid { // Bid adjustments are not allowed for location exclusions. // If IsExcluded is true, this element will be ignored. BidAdjustment = 10, PostalCode = "98052, WA US", IsExcluded = true } } }, RadiusTarget = new RadiusTarget2 { Bids = new[] { new RadiusTargetBid2 { BidAdjustment = 51, LatitudeDegrees = 47.755367, LongitudeDegrees = -122.091827, Radius = 11, //RadiusUnit = DistanceUnit.Kilometers } } } } }; // Update the same identified target as a Target2 object. // Going forward when getting the specified target Id, the Day and Hour elements of the legacy // Target object will be nil, since the target is being updated with a DayTime target. UpdateTargetsInLibrary2Async(new[] { target2 }); OutputStatusMessage("Updated the ad group level target as a Target2 object.\n"); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get Campaign Target: \n"); targets = await GetTargetsByIdsAsync(new[] { campaignTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get Campaign Target2: \n"); targets2 = await GetTargetsByIds2Async(new[] { campaignTargetId }); PrintTarget2(targets2[0]); // Get and print the Target with the legacy GetTargetsByIds operation OutputStatusMessage("Get AdGroup Target: \n"); targets = await GetTargetsByIdsAsync(new[] { adGroupTargetId }); PrintTarget(targets[0]); // Get and print the Target2 with the new GetTargetsByIds2 operation OutputStatusMessage("Get AdGroup Target2: \n"); targets2 = await GetTargetsByIds2Async(new[] { adGroupTargetId }); PrintTarget2(targets2[0]); // Get all new and existing targets in the customer library, whether or not they are // associated with campaigns or ad groups. var allTargetsInfo = await GetTargetsInfoFromLibraryAsync(); OutputStatusMessage("All target identifiers and names from the customer library: \n"); PrintTargetsInfo(allTargetsInfo); // Delete the campaign, ad group, and targets that were previously added. // DeleteCampaigns would remove the campaign and ad group, as well as the association // between ad groups and campaigns. To explicitly delete the association between an entity // and the target, use DeleteTargetFromCampaign and DeleteTargetFromAdGroup respectively. DeleteTargetFromCampaignAsync(campaignIds[0]); DeleteTargetFromAdGroupAsync(adGroupIds[0]); DeleteCampaignsAsync(authorizationData.AccountId, new[] { campaignIds[0] }); OutputStatusMessage(String.Format("Deleted CampaignId {0}\n", campaignIds[0])); // DeleteCampaigns deletes the association between the campaign and target, but does not // delete the target from the customer library. // Call the DeleteTargetsFromLibrary operation for each target that you want to delete. // You must specify an array with exactly one item. DeleteTargetsFromLibraryAsync(new[] { campaignTargetId }); OutputStatusMessage(String.Format("Deleted TargetId {0}\n", campaignTargetId)); DeleteTargetsFromLibraryAsync(new[] { adGroupTargetId }); OutputStatusMessage(String.Format("Deleted TargetId {0}\n", adGroupTargetId)); } // 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> /// Outputs the AdGroup. /// </summary> protected void OutputAdGroup(AdGroup adGroup) { if (adGroup != null) { OutputStatusMessage(string.Format("AdDistribution: {0}", adGroup.AdDistribution)); OutputStatusMessage(string.Format("AdRotation Type: {0}", adGroup.AdRotation != null ? adGroup.AdRotation.Type : null)); OutputStatusMessage(string.Format("BiddingModel: {0}", adGroup.BiddingModel)); OutputStatusMessage(string.Format("BroadMatchBid: {0}", adGroup.BroadMatchBid != null ? adGroup.BroadMatchBid.Amount : 0)); OutputStatusMessage(string.Format("ContentMatchBid: {0}", adGroup.ContentMatchBid)); if (adGroup.EndDate != null) { OutputStatusMessage(string.Format("EndDate: {0}/{1}/{2}", adGroup.EndDate.Month, adGroup.EndDate.Day, adGroup.EndDate.Year)); } OutputStatusMessage(string.Format("ExactMatchBid: {0}", adGroup.ExactMatchBid != null ? adGroup.ExactMatchBid.Amount : 0)); OutputStatusMessage("ForwardCompatibilityMap: "); if (adGroup.ForwardCompatibilityMap != null) { foreach (var pair in adGroup.ForwardCompatibilityMap) { OutputStatusMessage(string.Format("Key: {0}", pair.Key)); OutputStatusMessage(string.Format("Value: {0}", pair.Value)); } } OutputStatusMessage(string.Format("Id: {0}", adGroup.Id)); OutputStatusMessage(string.Format("Language: {0}", adGroup.Language)); OutputStatusMessage(string.Format("Name: {0}", adGroup.Name)); OutputStatusMessage(string.Format("NativeBidAdjustment: {0}", adGroup.NativeBidAdjustment)); OutputStatusMessage(string.Format("Network: {0}", adGroup.Network)); OutputStatusMessage(string.Format("PhraseMatchBid: {0}", adGroup.PhraseMatchBid != null ? adGroup.PhraseMatchBid.Amount : 0)); OutputStatusMessage(string.Format("PricingModel: {0}", adGroup.PricingModel)); if (adGroup.StartDate != null) { OutputStatusMessage(string.Format("StartDate: {0}/{1}/{2}", adGroup.StartDate.Month, adGroup.StartDate.Day, adGroup.StartDate.Year)); } OutputStatusMessage(string.Format("Status: {0}", adGroup.Status)); } }
public static string GetSidByAdGroup(AdGroup grp) { return GetList().Single(g => g.Group == grp).Sid; }
public IEnumerable<KeyValuePair<string, string>> GetUserListByAdGroup(AdGroup group) { return AdHelper.GetUserListByAdGroup(group); }