תחילת העבודה

במדריך הזה מוצגת סקירה קצרה של תחילת העבודה עם ספריית ה- .NET של Google Ads API.

התקנה

הקבצים הבינאריים של ספריות הלקוח מופצים באמצעות NuGet. כדי להשתמש בספריית הלקוח, מוסיפים הפניה ל-Nuget לחבילה Google.Ads.GoogleAds בפרויקט.

הגדרת ההרשאה

כדי לאשר את הקריאות ל-API, צריך לציין בספרייה את מזהה הלקוח, סוד הלקוח, אסימון הרענון וקוד המפתח.

אם כבר יש לך פרטי כניסה...

  • מעתיקים את הצומת GoogleAdsApi ואת הקטע GoogleAdsApi בצומת configSections מהקובץ App.config ב-GitHub לקובץ App.config / Web.config. אם השתמשתם ב-NuGet כדי להתקין את החבילה, הצמתים האלה יתווספו באופן אוטומטי לקובץ App.config או Web.config.
  • צריך לכלול את קוד המפתח, מזהה הלקוח, סוד הלקוח ואסימון הרענון ב-App.config או Web.config של האפליקציה. הקובץ App.config שכלול ב-GitHub מתועד היטב, אבל אפשר גם לעיין במדריך ההגדרה כדי לקבל מידע נוסף ולהשתמש בהגדרות תצורה חלופיות.

אם צריך ליצור פרטי כניסה...

  • פועלים לפי ההוראות במדריך האסימון למפתחים כדי לקבל את קוד המפתח, אם עוד לא עשיתם זאת.
  • פועלים לפי ההוראות במדריך לתהליך ליצירת מזהה לקוח, סוד לקוח ואסימון רענון של 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.V16.CampaignService);

// Make more calls to service class.

יצירת מופע של GoogleAdsClient

המחלקות הכי חשובות בספריית .NET של Google Ads API הן המחלקה GoogleAdsClient. היא מאפשרת ליצור מחלקת שירות מוגדרת מראש, שאפשר להשתמש בה לביצוע קריאות ל-API. GoogleAdsClient הוא ה-builder שמוגדר כברירת מחדל ויוצר אובייקט משתמש באמצעות ההגדרות שצוינו ב-App.config או Web.config של האפליקציה. אפשרויות שונות של הגדרות אישיות זמינות במדריך ההגדרה.

// Create a new GoogleAdsClient with the App.config settings.
GoogleAdsClient user = new GoogleAdsClient();

יצירת שירות

השיטה GoogleAdsClient מספקת את השיטה GetService שאפשר להשתמש בה כדי ליצור שירות Google Ads.

CampaignServiceClient campaignService = client.GetService(Services.V16.CampaignService);
// Now make calls to CampaignService.

אנחנו מספקים מחלקה Services שכוללת את כל הגרסאות והשירותים הנתמכים של API. השיטה GetService מקבלת את האובייקטים האלה של המספור כארגומנט בזמן יצירת השירות. לדוגמה, כדי ליצור מופע של CampaignServiceClient לגרסה V16 של Google Ads API, צריך לקרוא לשיטה GoogleAdsClient.GetService עם Services.V16.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 משיטה של גורם מטפל באירועים באפליקציית WinForm.

יש שתי דרכים לטפל בבעיה:

  1. משתמשים בספריית Grpc מהדור הקודם.

    אפשר להגדיר בנכס UseGrpcCore של GoogleAdsConfig שימוש בספריית Grpc.Core מדור קודם במקום בספריית ברירת המחדל של Grpc.Net.Client. השיטה הזו לא נבדקה באופן נרחב באפליקציות של .NET Framework, לכן יכול להיות שהיא לא תפתור את הבעיה. הנה קטע קוד לדוגמה:

    GoogleAdsConfig config = new GoogleAdsConfig();
    config.UseGrpcCore = true;
    GoogleAdsClient client = new GoogleAdsClient(config);
    
  2. שימוש בשיטות אסינכרוניות.

    אפשר להשתמש בשיטות אסינכרוניות כדי למנוע קיפאון. ריכזנו כאן כמה דוגמאות:

    SearchStream

    מתבצעת קריאה ל-SearchStream(), והתוצאות מאוכלסות בתצוגת רשימה.

    private async void button1_Click(object sender, EventArgs e)
    {
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V16.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.V16.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);
    }
    

ביטול שיטות אסינכרוניות

בתכנות אסינכרוני, אפשר להשתמש בפרמטר callSettings כדי להעביר פרמטר CancellationToken:

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.CancelAfter(3000);
CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token);

string query = "SELECT campaign.name FROM campaign";
var request = new SearchGoogleAdsStreamRequest()
{
    CustomerId = customerId.ToString(),
    Query = query,
};

GoogleAdsServiceClient googleAdsService = client.GetService(
    Services.V16.GoogleAdsService);

googleAdsService.SearchStream(request,
    delegate (SearchGoogleAdsStreamResponse resp)
    {
        foreach (GoogleAdsRow googleAdsRow in resp.Results)
        {
            // Process the row.
        }
    }, callSettings
);

טיפול בשגיאות

לא כל קריאה ל-API מצליחה. השרת עלול לגרום לשגיאות אם הקריאות ל-API נכשלות מסיבה כלשהי. חשוב לתעד שגיאות API ולטפל בהן כראוי.

מתבצעת הפעלה של המופע של GoogleAdsException כשמתרחשת שגיאת API. יש בו פרטים שיעזרו לכם להבין מה השתבש:

// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V16.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}");
}