כך משתמשים בספריית הלקוח ב- .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.V26.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.V26.CampaignService);
// Now make calls to CampaignService.
הספרייה מספקת מחלקה Services שמפרטת את כל גרסאות ה-API הנתמכות (כשגרסאות משניות כמו v25.1 משתמשות בגרסת ה-enum הראשית שלהן, Services.V25) והשירותים. ה-method GetService מקבלת את אובייקטי ה-enum האלה כארגומנט כשיוצרים את השירות. לדוגמה, כדי ליצור מופע של CampaignServiceClient לגרסה V26 של Google Ads API, צריך להפעיל את ה-method GoogleAdsClient.GetService עם הארגומנט Services.V26.CampaignService, כמו שמוצג בדוגמה הקודמת.
טיפול בשגיאות
לא כל קריאה ל-API מצליחה. השרת יכול להחזיר שגיאות אם הקריאות ל-API נכשלות מסיבה כלשהי. חשוב לתעד שגיאות ב-API ולטפל בהן בצורה מתאימה.
מופעלת דוגמה של GoogleAdsException כשמתרחשת שגיאת API. הוא כולל פרטים שיעזרו לכם להבין מה השתבש:
public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V26.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 משותף בכמה שרשורים הוא לא thread-safe, כי שינויים בהגדרות שאתם מבצעים במופע בשרשור אחד יכולים להשפיע על השירותים שאתם יוצרים בשרשורים אחרים.
עם זאת, פעולות לקריאה בלבד, כמו קבלת מופעי שירות חדשים ממופע GoogleAdsClient שלא משתנה וביצוע קריאות למספר שירותים במקביל, הן thread-safe.
כדי לבודד שינויים בהגדרות לכל שרשור, צריך ליצור מופע נפרד של GoogleAdsClient לכל משימה או שרשור של Worker:
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.
}
הקפדה על רספונסיביות של האפליקציה
הזמן שנדרש להשלמת הפעלות method ב-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.V26.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.V26.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}");
}
}