השימוש הבסיסי בספריית הלקוח של .NET הוא כדלקמן:
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Create the required service.
CampaignServiceClient campaignService =
client.GetService(Services.V25.CampaignService);
// Make calls to the service client.
הפעלת הלקוח והשירותים
כדי ליצור אינטראקציה עם Google Ads API, קודם צריך להגדיר ולהפעיל מופע של GoogleAdsClient, ואז להשתמש בו כדי ליצור את לקוחות שירות ה-API הספציפיים שאתם צריכים.
יצירת מכונה של GoogleAdsClient
הקלאס הכי חשוב בספריית .NET של Google Ads API הוא הקלאס GoogleAdsClient
. הוא מאפשר ליצור לקוח שירות שהוגדר מראש, שאפשר להשתמש בו כדי לבצע קריאות ל-API. כדי להגדיר אובייקט GoogleAdsClient, יוצרים אובייקט GoogleAdsConfig ומגדירים את המאפיינים הנדרשים. מידע נוסף זמין במדריך ההגדרה.
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Modify the GoogleAdsClient configuration afterwards if needed.
client.Config.LoginCustomerId = "INSERT_UPDATED_LOGIN_CUSTOMER_ID_HERE";
יצירת שירות
GoogleAdsClient מספק method GetService שאפשר להשתמש בו כדי ליצור לקוח של שירות API.
CampaignServiceClient campaignService = client.GetService(
Services.V25.CampaignService);
// Now make calls to CampaignService.
הספרייה מספקת מחלקה Services שמפרטת את כל גרסאות ה-API הנתמכות (כשגרסאות משניות כמו v25.1 משתמשות בגרסת ה-enum הראשית שלהן, Services.V25) והשירותים. השיטה GetService מקבלת את אובייקטי הספירה האלה כארגומנט כשיוצרים את השירות. לדוגמה, כדי ליצור מופע של CampaignServiceClient לגרסה V25 של Google Ads API, קוראים ל-method GoogleAdsClient.GetService עם Services.V25.CampaignService כארגומנט, כמו בדוגמה הקודמת.
טיפול בשגיאות
לא כל קריאה ל-API מצליחה. השרת יכול להחזיר שגיאות אם הקריאות ל-API נכשלות מסיבה כלשהי. חשוב לתעד שגיאות ב-API ולטפל בהן בצורה מתאימה.
מופעלת דוגמה של GoogleAdsException כשמתרחשת שגיאת API. הוא מכיל פרטים שיעזרו לכם להבין מה הייתה הבעיה:
public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V25.GoogleAdsService); // Create a query that will retrieve all campaigns. string query = @"SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"; try { // Issue a search request. googleAdsService.SearchStream(customerId.ToString(), query, delegate (SearchGoogleAdsStreamResponse resp) { foreach (GoogleAdsRow googleAdsRow in resp.Results) { Console.WriteLine("Campaign with ID {0} and name '{1}' was found.", googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name); } } ); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
Thread safety
שינוי מצב ההגדרה של מופע GoogleAdsClient משותף בכמה שרשורים הוא לא בטוח לשרשור, כי שינויים בהגדרות שאתם מבצעים במופע בשרשור אחד יכולים להשפיע על השירותים שאתם יוצרים בשרשורים אחרים.
עם זאת, פעולות לקריאה בלבד, כמו קבלת מופעים חדשים של שירות ממופע GoogleAdsClient שלא משתנה וביצוע קריאות לכמה שירותים במקביל, הן בטוחות לשימוש עם שרשורים.
כדי לבודד שינויים בהגדרות של כל שרשור, יוצרים מופע נפרד של GoogleAdsClient לכל משימת עובד או שרשור:
GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();
Task task1 = Task.Run(() => AddAdGroups(client1));
Task task2 = Task.Run(() => AddAdGroups(client2));
await Task.WhenAll(task1, task2);
public void AddAdGroups(GoogleAdsClient client)
{
// Perform operations with client.
}
הקפדה על רספונסיביות של האפליקציה
השלמת קריאות לשיטות של Google Ads API יכולה להימשך זמן מה, בהתאם לגודל הבקשות. כדי שהאפליקציה תמשיך להגיב, צריך לפעול לפי השלבים הבאים:
שימוש בספריית Grpc.Core למסגרות ממשק משתמש מדור קודם
אם אתם מפתחים אפליקציה שמיועדת ל- .NET Framework ומשתמשת בטכנולוגיית ממשק משתמש מדור קודם, כמו ASP.NET Web Forms או WinForms, אתם יכולים להפעיל את ספריית התעבורה מדור קודם Grpc.Core באופן הבא:
GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);
שימוש בשיטות אסינכרוניות
אתם יכולים להשתמש בשיטות אסינכרוניות כדי שהאפליקציה תמשיך להגיב. ריכזנו כאן כמה דוגמאות.
שליפת רשימת הקמפיינים ואכלוס של ListView
private async void OnRetrieveCampaignsButtonClick(object sender, EventArgs e)
{
try
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V25.GoogleAdsService);
// Create a query that will retrieve all campaigns.
string query = @"SELECT
campaign.id,
campaign.name,
campaign.network_settings.target_content_network
FROM campaign
ORDER BY campaign.id";
List<ListViewItem> items = new List<ListViewItem>();
await googleAdsService.SearchStreamAsync(
customerId.ToString(),
query,
(SearchGoogleAdsStreamResponse resp) =>
{
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
ListViewItem item = new ListViewItem();
item.Text = googleAdsRow.Campaign.Id.ToString();
item.SubItems.Add(googleAdsRow.Campaign.Name);
items.Add(item);
}
}
);
listView1.Items.AddRange(items.ToArray());
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}
עדכון תקציב הקמפיין והצגת התראה בתיבת הודעה
private async void OnUpdateBudgetButtonClick(object sender, EventArgs e)
{
try
{
// Get the CampaignBudgetService.
CampaignBudgetServiceClient budgetService = client.GetService(
Services.V25.CampaignBudgetService);
// Create the campaign budget.
CampaignBudget budget = new CampaignBudget()
{
Name = "Interplanetary Cruise Budget #" +
ExampleUtilities.GetRandomString(),
DeliveryMethod = BudgetDeliveryMethod.Standard,
AmountMicros = 500000
};
// Create the operation.
CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
{
Create = budget
};
// Create the campaign budget asynchronously.
MutateCampaignBudgetsResponse response =
await budgetService.MutateCampaignBudgetsAsync(
customerId.ToString(),
new CampaignBudgetOperation[] { budgetOperation });
MessageBox.Show(response.Results[0].ResourceName);
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}