/
AddCustomerMatchUserList.cs
376 lines (346 loc) · 16.7 KB
/
AddCustomerMatchUserList.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// 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.V8.Common;
using Google.Ads.GoogleAds.V8.Errors;
using Google.Ads.GoogleAds.V8.Resources;
using Google.Ads.GoogleAds.V8.Services;
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using static Google.Ads.GoogleAds.V8.Enums.CustomerMatchUploadKeyTypeEnum.Types;
using static Google.Ads.GoogleAds.V8.Enums.OfflineUserDataJobTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V8
{
/// <summary>
/// This code example uses Customer Match to create a new user list (a.k.a. audience) and adds
/// users to it.
///
/// Note: It may take up to several hours for the list to be populated with users.
/// Email addresses must be associated with a Google account.
/// For privacy purposes, the user list size will show as zero until the list has
/// at least 1,000 users. After that, the size will be rounded to the two most
/// significant digits.
/// </summary>
public class AddCustomerMatchUserList : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddCustomerMatchUserList"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the user list is added.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the user list is added.")]
public long CustomerId { 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 user list is added.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
return 0;
});
AddCustomerMatchUserList codeExample = new AddCustomerMatchUserList();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId);
}
private const int POLL_FREQUENCY_SECONDS = 1;
private const int MAX_TOTAL_POLL_INTERVAL_SECONDS = 60;
private static SHA256 digest = SHA256.Create();
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example uses Customer Match to create a new user list (a.k.a. audience) " +
"and adds users to it. \nNote: It may take up to several hours for the list to be " +
"populated with users. Email addresses must be associated with a Google account. For " +
"privacy purposes, the user list size will show as zero until the list has at least " +
"1,000 users. After that, the size will be rounded to the two most significant digits.";
/// <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 user list is added.
/// </param>
public void Run(GoogleAdsClient client, long customerId)
{
try
{
string userListResourceName = CreateCustomerMatchUserList(client, customerId);
AddUsersToCustomerMatchUserList(client, customerId, userListResourceName);
PrintCustomerMatchUserListInfo(client, customerId, userListResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates the customer match user list.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the user list is added.
/// </param>
/// <returns>The resource name of the newly created user list</returns>
private string CreateCustomerMatchUserList(GoogleAdsClient client, long customerId)
{
// Get the UserListService.
UserListServiceClient service = client.GetService(Services.V8.UserListService);
// Creates the user list.
UserList userList = new UserList()
{
Name = $"Customer Match list# {ExampleUtilities.GetShortRandomString()}",
Description = "A list of customers that originated from email and physical" +
" addresses",
// Customer Match user lists can use a membership life span of 10000 to
// indicate unlimited; otherwise normal values apply.
// Sets the membership life span to 30 days.
MembershipLifeSpan = 30,
CrmBasedUserList = new CrmBasedUserListInfo()
{
UploadKeyType = CustomerMatchUploadKeyType.ContactInfo
}
};
// Creates the user list operation.
UserListOperation operation = new UserListOperation()
{
Create = userList
};
// Issues a mutate request to add the user list and prints some information.
MutateUserListsResponse response = service.MutateUserLists(
customerId.ToString(), new[] { operation });
string userListResourceName = response.Results[0].ResourceName;
Console.WriteLine($"User list with resource name '{userListResourceName}' " +
$"was created.");
return userListResourceName;
}
/// <summary>
/// Creates and executes an asynchronous job to add users to the Customer Match user list.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which calls are made.
/// </param>
/// <param name="userListResourceName">the resource name of the Customer Match user list
/// to add users to</param>
// [START add_customer_match_user_list]
private static void AddUsersToCustomerMatchUserList(GoogleAdsClient client,
long customerId, string userListResourceName)
{
// Get the OfflineUserDataJobService.
OfflineUserDataJobServiceClient service = client.GetService(
Services.V8.OfflineUserDataJobService);
// Creates a new offline user data job.
OfflineUserDataJob offlineUserDataJob = new OfflineUserDataJob()
{
Type = OfflineUserDataJobType.CustomerMatchUserList,
CustomerMatchUserListMetadata = new CustomerMatchUserListMetadata()
{
UserList = userListResourceName
}
};
// Issues a request to create the offline user data job.
CreateOfflineUserDataJobResponse response1 = service.CreateOfflineUserDataJob(
customerId.ToString(), offlineUserDataJob);
string offlineUserDataJobResourceName = response1.ResourceName;
Console.WriteLine($"Created an offline user data job with resource name: " +
$"'{offlineUserDataJobResourceName}'.");
AddOfflineUserDataJobOperationsRequest request =
new AddOfflineUserDataJobOperationsRequest()
{
ResourceName = offlineUserDataJobResourceName,
Operations = { BuildOfflineUserDataJobOperations() },
EnablePartialFailure = true,
};
// Issues a request to add the operations to the offline user data job.
AddOfflineUserDataJobOperationsResponse response2 =
service.AddOfflineUserDataJobOperations(request);
// Prints the status message if any partial failure error is returned.
// Note: The details of each partial failure error are not printed here,
// you can refer to the example HandlePartialFailure.cs to learn more.
if (response2.PartialFailureError != null)
{
// Extracts the partial failure from the response status.
GoogleAdsFailure partialFailure = response2.PartialFailure;
Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " +
$"occurred");
}
Console.WriteLine("The operations are added to the offline user data job.");
// Issues an asynchronous request to run the offline user data job for executing
// all added operations.
Operation<Empty, Empty> operationResponse =
service.RunOfflineUserDataJob(offlineUserDataJobResourceName);
Console.WriteLine("Asynchronous request to execute the added operations started."); ;
Console.WriteLine("Waiting until operation completes.");
// PollUntilCompleted() implements a default back-off policy for retrying. You can
// tweak the polling behaviour using a PollSettings as illustrated below.
operationResponse.PollUntilCompleted(new PollSettings(
Expiration.FromTimeout(TimeSpan.FromSeconds(MAX_TOTAL_POLL_INTERVAL_SECONDS)),
TimeSpan.FromSeconds(POLL_FREQUENCY_SECONDS)));
if (operationResponse.IsCompleted)
{
Console.WriteLine($"Offline user data job with resource name " +
$"'{offlineUserDataJobResourceName}' has finished.");
}
else
{
Console.WriteLine($"Offline user data job with resource name" +
$" '{offlineUserDataJobResourceName}' is pending after " +
$"{MAX_TOTAL_POLL_INTERVAL_SECONDS} seconds.");
}
}
// [END add_customer_match_user_list]
/// <summary>
/// Builds and returns offline user data job operations to add one user identified by an
/// email address and one user identified based on a physical address.
/// </summary>
/// <returns>An array with the operations</returns>
private static OfflineUserDataJobOperation[] BuildOfflineUserDataJobOperations()
{
// [START add_customer_match_user_list_2]
// Creates a first user data based on an email address.
UserData userDataWithEmailAddress = new UserData()
{
UserIdentifiers = {
new UserIdentifier()
{
// Hash normalized email addresses based on SHA-256 hashing algorithm.
HashedEmail = NormalizeAndHash("customer@example.com")
}
}
};
// Creates a second user data based on a physical address.
UserData userDataWithPhysicalAddress = new UserData()
{
UserIdentifiers =
{
new UserIdentifier()
{
AddressInfo = new OfflineUserAddressInfo()
{
// First and last name must be normalized and hashed.
HashedFirstName = NormalizeAndHash("John"),
HashedLastName = NormalizeAndHash("Doe"),
// Country code and zip code are sent in plain text.
CountryCode = "US",
PostalCode = "10011"
}
}
}
};
// [END add_customer_match_user_list_2]
// Creates the operations to add the two users.
return new OfflineUserDataJobOperation[]
{
new OfflineUserDataJobOperation()
{
Create = userDataWithEmailAddress
},
new OfflineUserDataJobOperation()
{
Create = userDataWithPhysicalAddress
}
};
}
/// <summary>
/// Prints information about the Customer Match user list.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which calls are made.
/// </param>
/// <param name="userListResourceName">The resource name of the Customer Match user list
/// to print information about.</param>
private void PrintCustomerMatchUserListInfo(GoogleAdsClient client, long customerId,
string userListResourceName)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient service =
client.GetService(Services.V8.GoogleAdsService);
// Creates a query that retrieves the user list.
string query =
"SELECT user_list.size_for_display, user_list.size_for_search " +
"FROM user_list " +
$"WHERE user_list.resource_name = '{userListResourceName}'";
// Issues a search stream request.
service.SearchStream(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse resp)
{
// Display the results.
foreach (GoogleAdsRow userListRow in resp.Results)
{
UserList userList = userListRow.UserList;
Console.WriteLine("The estimated number of users that the user list " +
$"'{userList.ResourceName}' has is {userList.SizeForDisplay}" +
$" for Display and {userList.SizeForSearch} for Search.");
}
}
);
Console.WriteLine("Reminder: It may take several hours for the user list to be " +
"populated with the users so getting zeros for the estimations is expected.");
}
/// <summary>
/// Normalizes and hashes a string value.
/// </summary>
/// <param name="value">The value to normalize and hash.</param>
/// <returns>The normalized and hashed value.</returns>
private static string NormalizeAndHash(string value)
{
return ToSha256String(digest, ToNormalizedValue(value));
}
/// <summary>
/// Hash a string value using SHA-256 hashing algorithm.
/// </summary>
/// <param name="digest">Provides the algorithm for SHA-256.</param>
/// <param name="value">The string value (e.g. an email address) to hash.</param>
/// <returns>The hashed value.</returns>
private static string ToSha256String(SHA256 digest, string value)
{
byte[] digestBytes = digest.ComputeHash(Encoding.UTF8.GetBytes(value));
// Convert the byte array into an unhyphenated hexadecimal string.
return BitConverter.ToString(digestBytes).Replace("-", string.Empty);
}
/// <summary>
/// Removes leading and trailing whitespace and converts all characters to
/// lower case.
/// </summary>
/// <param name="value">The value to normalize.</param>
/// <returns>The normalized value.</returns>
private static string ToNormalizedValue(string value)
{
return value.Trim().ToLower();
}
}
}