המדריך הזה מספק סקירה כללית קצרה על תחילת העבודה עם Google Ads API ספריית .NET
התקנה
הקבצים הבינאריים של ספריות הלקוח מופצים באמצעות NuGet. הוספת מסמך עזר של NuGet
אל Google.Ads.GoogleAds
חבילה בפרויקט לשימוש
את ספריית הלקוח.
הגדרת הרשאה
כדי לאשר את הקריאות שלך ל-API, עליך לציין את מזהה הלקוח, סוד הלקוח, את אסימון הרענון ואת קוד המפתח של הספרייה.
אם צריך ליצור פרטי כניסה
- צריך לפעול לפי המדריך לאסימון למפתחים כדי לקבל את קוד המפתח שלכם, אם עדיין אין לכם אחד.
- פועלים בהתאם לתהליך העבודה של OAuth למחשב. במדריך ליצירת מזהה לקוח, סוד לקוח ואסימון רענון.
אם כבר יש לכם פרטי כניסה
- מעתיקים את הצומת
GoogleAdsApi
ואת הקטעGoogleAdsApi
שמתחת ל הצומתconfigSections
מהקובץApp.config
ב- GitHub לקובץApp.config
/Web.config
שלך. אם השתמשת ב-NuGet כדי להתקין את החבילה, הצמתים האלה יתווספו באופן אוטומטיApp.config
/ קובץWeb.config
. - כוללים את קוד המפתח, מזהה הלקוח, סוד הלקוח ואסימון הרענון
ב
App.config
/Web.config
של האפליקציה.
App.config
שמופיע ב-GitHub מתועד היטב, אבל אפשר גם לעיין
מדריך להגדרה
כדי לקבל מידע נוסף ולהשתמש בדרכים חלופיות להגדרת ספריית הלקוח,
כמו משתני סביבה.
ביצוע קריאה ל-API
השימוש הבסיסי בספריית הלקוח הוא:
// Create a Google Ads client.
GoogleAdsClient client = new GoogleAdsClient();
// Create the required service.
CampaignServiceClient campaignService =
client.GetService(Services.V17.CampaignService);
// Make more calls to service class.
יצירת מופע של Google AdsClient
הסוגים החשובים ביותר בספריית .NET של Google Ads API הם
כיתה אחת (GoogleAdsClient
). היא מאפשרת ליצור סיווג שירות מוגדר מראש
שאפשר להשתמש בהן כדי לשלוח קריאות ל-API. GoogleAdsClient
מספק ברירת מחדל
שיוצר אובייקט משתמש באמצעות ההגדרות שצוינו
App.config
/ Web.config
של האפליקציה. מידע נוסף זמין בקטע הגדרות
מדריך להגדרה
אפשרויות.
// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();
יצירת שירות
GoogleAdsClient
מספק method GetService
שניתן להשתמש בה כדי ליצור
שירות מודעות.
CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);
// Now make calls to CampaignService.
אנחנו מספקים מחלקה Services
שמפרטת את כל גרסאות ה-API הנתמכות
שירותים שונים. השיטה GetService
מקבלת את אובייקטי הספירה האלה כארגומנט
במהלך יצירת השירות. לדוגמה, כדי ליצור מופע של
CampaignServiceClient
לגרסה V17
של Google Ads API,
צריך להפעיל את ה-method GoogleAdsClient.GetService
עם
Services.V17.CampaignService
כארגומנט, כפי שמוצג
בדוגמה הקודמת.
בטיחות השרשורים
לא בטוח לשתף מופע GoogleAdsClient
בין כמה שרשורים,
כי שינויי ההגדרות שמבצעים במכונה בשרשור אחד עלולים
ישפיעו על השירותים שתיצרו בשרשורים אחרים. פעולות כמו קבלת
מכונות שירות חדשות ממכונה של GoogleAdsClient
ומבצעים קריאות ל-
מספר שירותים במקביל הם בטוחים בשרשור.
אפליקציה מרובת שרשורים תיראה כך:
GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();
Thread userThread1 = new Thread(addAdGroups);
Thread userThread2 = new Thread(addAdGroups);
userThread1.start(client1);
userThread2.start(client2);
userThread1.join();
userThread2.join();
public void addAdGroups(object data) {
GoogleAdsClient client = (GoogleAdsClient) data;
// Do more operations here.
...
}
הימנעות מקפיאות באפליקציות .NET Framework
שיטות סינכרוניות עלולות לגרום לחלק מהאפליקציות של .NET Framework להקפיא. דוגמה נפוצה היא ביצוע קריאות ל-API מ-method של הגורם המטפל באירועים של אפליקציה ב-WinForm.
יש שתי דרכים לטפל בבעיה הזו:
משתמשים בספריית Grapc בגרסה הקודמת.
אפשר להגדיר את המאפיין
UseGrpcCore
שלGoogleAdsConfig
כך שישתמש ספרייתGrpc.Core
מדור קודם במקום ספרייתGrpc.Net.Client
המוגדרת כברירת מחדל. השיטה הזו לא נבדקה בצורה נרחבת באפליקציות .NET Framework כך שיכול להיות שזה לא יפתור את הבעיה. הנה קטע קוד לדוגמה:GoogleAdsConfig config = new GoogleAdsConfig(); config.UseGrpcCore = true; GoogleAdsClient client = new GoogleAdsClient(config);
בדף התמיכה של gRPC יש מידע נוסף פרטים על ההבדלים בין הספרייה
Grpc.Core
מהדור הקודם לבין ספרייתGrpc.Net.Client
שמוגדרת כברירת מחדל.משתמשים בשיטות אסינכרוניות.
אתם יכולים להשתמש בשיטות אסינכרוניות כדי למנוע קיפאון. הנה כמה דוגמאות:
SearchStream
מתבצעת קריאה אל
SearchStream()
, והתוצאות מאוכלסים בתצוגת רשימה.private async void button1_Click(object sender, EventArgs e) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V17.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
items = new List (); Task t = googleAdsService.SearchStreamAsync(customerId.ToString(), query, delegate (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); } } ); await t; listView1.Items.AddRange(items.ToArray()); } תקציב קמפיין
נוצרת קריאה ל-CampaignBudget, ושם המשאב של התקציב החדש הוא מוצגת באמצעות התראה
MessageBox
.private async void button2_Click(object sender, EventArgs e) { // Get the BudgetService. CampaignBudgetServiceClient budgetService = client.GetService( Services.V17.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. Task
t = budgetService.MutateCampaignBudgetsAsync( customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation }); await t; MutateCampaignBudgetsResponse response = t.Result; MessageBox.Show(response.Results[0].ResourceName); }
טיפול בשגיאות
לא כל קריאה ל-API תצליח. השרת עלול לזרוק שגיאות אם מתבצעת קריאה ל-API נכשלים מסיבה כלשהי. חשוב לתעד את השגיאות ב-API ולטפל בהן המתאים.
מופע של GoogleAdsException
מועבר כשמתרחשת שגיאת API. יש בו
כדי להבין מה השתבש:
// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);
// Create a campaign for update.
Campaign campaignToUpdate = new Campaign()
{
ResourceName = ResourceNames.Campaign(customerId, campaignId),
// More fields to update.
// ...
};
// Create the operation.
CampaignOperation operation = new CampaignOperation()
{
Update = campaignToUpdate,
UpdateMask = FieldMasks.AllSetFieldsOf(campaignToUpdate)
};
try
{
// Update the campaign.
MutateCampaignsResponse response = campaignService.MutateCampaigns(
customerId.ToString(), new CampaignOperation[] { operation });
// Display the results.
// ...
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
// Can examine to get more error details.
Console.WriteLine($"Failure: {e.Failure}");
// Can be shared with Google for further troubleshooting.
Console.WriteLine($"Request ID: {e.RequestId}");
}