/
RemoveFlightsFeedItemAttributeValue.cs
345 lines (305 loc) · 16.1 KB
/
RemoveFlightsFeedItemAttributeValue.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V8.Errors;
using Google.Ads.GoogleAds.V8.Resources;
using Google.Ads.GoogleAds.V8.Services;
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V8.Enums.FlightPlaceholderFieldEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V8
{
/// <summary>
/// Removes a feed item attribute value of a feed item in a flights feed. To create a flights
/// feed, run the AddFlightsFeed example. This example is specific to feeds of type
/// DYNAMIC_FLIGHT. The attribute you are removing must be present on the feed. /// This example
/// is specifically for removing an attribute of a flights feed item, but it can also be changed
/// to work with other feed types. /// To make this work with other feed types, replace the
/// FlightPlaceholderField enum with the equivalent one of your feed type, and replace the
/// appropriate attribute names in the GetFeeds method.
/// </summary>
public class RemoveFlightsFeedItemAttributeValue : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="RemoveFlightsFeedItemAttributeValue"/>
/// example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// The Feed ID to which the feed item belongs.
/// </summary>
[Option("feedId", Required = true, HelpText =
"The Feed ID to which the feed item belongs.")]
public long FeedId { get; set; }
/// <summary>
/// The ID of the feed item to be updated.
/// </summary>
[Option("feedItemId", Required = true, HelpText =
"The ID of the feed item to be updated.")]
public long FeedItemId { get; set; }
/// <summary>
/// The flight placeholder field name for the attribute to be removed.
/// </summary>
[Option("flightPlaceholderFieldName", Required = true, HelpText =
"The flight placeholder field name for the attribute to be removed.")]
public string FlightPlaceholderFieldName { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The Feed ID to which the feed item belongs.
options.FeedId = long.Parse("INSERT_FEED_ID_HERE");
// The ID of the feed item to be updated.
options.FeedItemId = long.Parse("INSERT_FEED_ITEM_ID_HERE");
// The flight placeholder field name for the attribute to be removed.
options.FlightPlaceholderFieldName =
"INSERT_FLIGHT_PLACEHOLDER_FIELD_NAME_HERE";
return 0;
});
RemoveFlightsFeedItemAttributeValue codeExample =
new RemoveFlightsFeedItemAttributeValue();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.FeedId,
options.FeedItemId, options.FlightPlaceholderFieldName);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"Removes a feed item attribute value of a feed item in a flights feed. To create a " +
"flights feed, run the AddFlightsFeed example. This example is specific to feeds of " +
"type DYNAMIC_FLIGHT. The attribute you are removing must be present on the feed.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="feedId">The Feed ID to which the feed item belongs.</param>
/// <param name="feedItemId">The ID of the feed item to be updated.</param>
/// <param name="flightPlaceholderFieldName">
/// The flight placeholder field name for the attribute to be removed.
/// </param>
public void Run(GoogleAdsClient client, long customerId, long feedId, long feedItemId,
string flightPlaceholderFieldName)
{
// Creates the Feed Item service client.
FeedItemServiceClient feedItemServiceClient = client.GetService(
Services.V8.FeedItemService);
try
{
// Gets a map of the placeholder values to feed attributes.
Dictionary<FlightPlaceholderField, FeedAttribute> placeholdersToFeedAttributesMap =
GetFeed(client, customerId, feedId);
// Removes the attribute from the feed item.
FlightPlaceholderField flightPlaceholderField =
(FlightPlaceholderField) Enum.Parse(typeof(FlightPlaceholderField),
flightPlaceholderFieldName, true);
FeedItem feedItem = RemoveAttributeValueFromFeedItem(client, customerId, feedId,
feedItemId, placeholdersToFeedAttributesMap, flightPlaceholderField);
// [START remove_flights_feed_item_attribute_value_1] Creates the operation.
FeedItemOperation operation = new FeedItemOperation
{
Update = feedItem,
UpdateMask = FieldMasks.AllSetFieldsOf(feedItem)
};
// Updates the feed item and prints the results.
MutateFeedItemsResponse response = feedItemServiceClient.MutateFeedItems
(customerId.ToString(), new[] { operation });
foreach (MutateFeedItemResult result in response.Results)
{
Console.WriteLine("Updated feed item with resource name " +
$"'{result.ResourceName}'.");
}
// [END remove_flights_feed_item_attribute_value_1]
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
catch (Exception e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
throw;
}
}
/// <summary>
/// Retrieves details about a feed. The initial query retrieves the FeedAttributes, or
/// columns, of the feed. Each FeedAttribute will also include the FeedAttributeId, which
/// will be used in a subsequent step. The example then inserts a new key, value pair into
/// a map for each FeedAttribute, which is the return value of the method. The keys are the
/// placeholder types that the columns will be. The values are the FeedAttributes.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID that has the flights feed.</param>
/// <param name="feedId">The feed ID for which to get details.</param>
/// <returns>A mapping of FlightPlaceholderFields to FeedAttributes.</returns>
public Dictionary<FlightPlaceholderField, FeedAttribute> GetFeed(
GoogleAdsClient client, long customerId, long feedId)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V8.GoogleAdsService);
string feedResourceName = ResourceNames.Feed(customerId, feedId);
// Constructs the query.
string query = "SELECT feed.attributes FROM feed WHERE feed.resource_name = " +
$"'{feedResourceName}'";
// Constructs the request.
SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
{
CustomerId = customerId.ToString(),
Query = query
};
// Issues the search request and get the first result, since we only need the single
// feed item we created previously.
GoogleAdsRow googleAdsRow = googleAdsService.Search(request).First();
// Gets the attributes list from the feed and creates a map with keys of each attribute
// and values of each corresponding ID.
Dictionary<FlightPlaceholderField, FeedAttribute> feedAttributes =
new Dictionary<FlightPlaceholderField, FeedAttribute>();
// Loops through the feed attributes to populate the map.
foreach (FeedAttribute feedAttribute in googleAdsRow.Feed.Attributes)
{
switch (feedAttribute.Name)
{
case "Flight Description":
feedAttributes[FlightPlaceholderField.FlightDescription] = feedAttribute;
break;
case "Destination ID":
feedAttributes[FlightPlaceholderField.DestinationId] = feedAttribute;
break;
case "Flight Price":
feedAttributes[FlightPlaceholderField.FlightPrice] = feedAttribute;
break;
case "Flight Sale Price":
feedAttributes[FlightPlaceholderField.FlightSalePrice] = feedAttribute;
break;
case "Final URLs":
feedAttributes[FlightPlaceholderField.FinalUrls] = feedAttribute;
break;
// The full list of FlightPlaceholderFields can be found here
// https://developers.google.com/google-ads/api/reference/rpc/latest/FlightPlaceholderFieldEnum.FlightPlaceholderField
default:
throw new Exception("Invalid attribute name.");
}
}
return feedAttributes;
}
/// <summary>
/// Removes an attribute value from the specified feed item.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID that has the flights feed.</param>
/// <param name="feedId">The feed ID that contains the target feed item.</param>
/// <param name="feedItemId">The feed item ID that will be updated.</param>
/// <param name="placeholdersToFeedAttributesMap">
/// A mapping of FlightPlaceholderFields to FeedAttributes.
/// </param>
/// <param name="flightPlaceholderFieldName">The attributed field name to remove.</param>
/// <returns>The modified feed item.</returns>
/// <exception cref="ArgumentException">
/// If the specified attribute was not found in the feed item.
/// </exception>
// [START remove_flights_feed_item_attribute_value]
private FeedItem RemoveAttributeValueFromFeedItem(GoogleAdsClient client, long customerId,
long feedId, long feedItemId,
Dictionary<FlightPlaceholderField, FeedAttribute> placeholdersToFeedAttributesMap,
FlightPlaceholderField flightPlaceholderFieldName)
{
// Gets the ID of the FeedAttribute for the placeholder field.
long attributeId = placeholdersToFeedAttributesMap[flightPlaceholderFieldName].Id;
// Retrieves the feed item and its associated attributes based on its resource name.
FeedItem feedItem = GetFeedItem(client, customerId, feedId, feedItemId);
//Creates the FeedItemAttributeValue that will be updated.
FeedItemAttributeValue feedItemAttributeValue = new FeedItemAttributeValue
{
FeedAttributeId = attributeId
};
// Gets the index of the attribute value that will be removed.
int attributeIndex = feedItem.AttributeValues
.Select((item, index) => new { item, index })
.Where(itemIndexPair =>
itemIndexPair.item.FeedAttributeId == feedItemAttributeValue.FeedAttributeId)
.Select(itemIndexPair => itemIndexPair.index + 1)
.FirstOrDefault() - 1;
if (attributeIndex == -1)
{
throw new ArgumentException("No matching feed attribute found for " +
$"value '{feedItemAttributeValue}'.");
}
// Returns the feed item with the removed FeedItemAttributeValue. Any
// FeedItemAttributeValues that are not included in the updated FeedItem will be
// removed from the FeedItem, which is why you must create the FeedItem from the
// existing FeedItem and set the field(s) that will be removed.
feedItem.AttributeValues.RemoveAt(attributeIndex);
return feedItem;
}
// [END remove_flights_feed_item_attribute_value]
/// <summary>
/// Retrieves a feed item and its attribute values given a resource name.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The client customer ID.</param>
/// <param name="feedId">The feed ID that contains the target feed item.</param>
/// <param name="feedItemId">The feed item ID that will be updated.</param>
/// <returns>FeedItem with the given resource name.</returns>
private FeedItem GetFeedItem(GoogleAdsClient client, long customerId,
long feedId, long feedItemId)
{
// Gets the Google Ads service.
GoogleAdsServiceClient googleAdsServiceClient = client.GetService(
Services.V8.GoogleAdsService);
// Constructs the resource name for the feed item.
string feedItemResourceName = ResourceNames.FeedItem(customerId, feedId, feedItemId);
// Constructs the query.
string query = $@"
SELECT feed_item.attribute_values
FROM feed_item
WHERE feed_item.resource_name = '{feedItemResourceName}'";
// Issues the search request.
PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> searchResponse =
googleAdsServiceClient.Search(customerId.ToString(), query);
// Returns the feed item attribute values.
return searchResponse.First().FeedItem;
}
}
}