שימוש בסיסי

כך משתמשים בספריית הלקוח ב-‎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 הנתמכות (כאשר גרסאות משניות כמו v26.1 משתמשות ב-enum של הגרסה הראשית שלהן, Services.V26) והשירותים. ה-method‏ GetService מקבלת את אובייקטי ה-enum האלה כארגומנט כשיוצרים את השירות. לדוגמה, כדי ליצור מופע של CampaignServiceClient לגרסה V26 של Google Ads API, צריך להפעיל את השיטה 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.
}

שמירה על מהירות התגובה של האפליקציה

הפעלות של methods ב-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}");
    }
}