Penggunaan dasar

Penggunaan dasar library klien .NET adalah sebagai berikut:

// 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.

Melakukan inisialisasi klien dan layanan

Untuk berinteraksi dengan Google Ads API, pertama-tama konfigurasi dan buat instance GoogleAdsClient, lalu gunakan untuk membuat klien layanan API tertentu yang Anda butuhkan.

Buat instance GoogleAdsClient

Class yang paling penting dalam library .NET Google Ads API adalah class GoogleAdsClient. Dengan library ini, Anda dapat membuat klien layanan yang telah dikonfigurasi sebelumnya dan dapat digunakan untuk melakukan panggilan API. Untuk mengonfigurasi objek GoogleAdsClient, buat objek GoogleAdsConfig dan tetapkan properti yang diperlukan. Lihat Panduan konfigurasi untuk mempelajari lebih lanjut.

// 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";

Membuat service

GoogleAdsClient menyediakan metode GetService yang dapat digunakan untuk membuat klien layanan API.

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

Library ini menyediakan class Services yang mencantumkan semua versi API yang didukung (dengan rilis kecil seperti v25.1 menggunakan enum versi utamanya, Services.V25) dan layanan. Metode GetService menerima objek enumerasi ini sebagai argumen saat membuat layanan. Misalnya, untuk membuat instance CampaignServiceClient untuk Google Ads API versi V25, panggil metode GoogleAdsClient.GetService dengan Services.V25.CampaignService sebagai argumen, seperti yang ditunjukkan dalam contoh sebelumnya.

Penanganan error

Tidak semua panggilan API berhasil. Server dapat menampilkan error jika panggilan API Anda gagal karena alasan tertentu. Penting untuk mencatat error API dan menanganinya dengan tepat.

Instance GoogleAdsException ditampilkan saat terjadi error API. Log ini berisi detail untuk membantu Anda mengetahui apa yang salah:

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;
    }
}
      

Keamanan thread

Mengubah status konfigurasi instance GoogleAdsClient bersama di beberapa thread tidak aman untuk thread, karena perubahan konfigurasi yang Anda lakukan pada instance di satu thread dapat memengaruhi layanan yang Anda buat di thread lain. Namun, operasi hanya baca seperti mendapatkan instance layanan baru dari instance GoogleAdsClient yang tidak berubah dan melakukan panggilan ke beberapa layanan secara paralel bersifat aman untuk thread.

Untuk mengisolasi perubahan konfigurasi per thread, buat instance GoogleAdsClient terpisah per tugas atau thread pekerja:

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.
}

Menjaga aplikasi Anda tetap responsif

Panggilan metode Google Ads API dapat memerlukan waktu beberapa saat untuk diselesaikan, bergantung pada ukuran permintaan. Agar aplikasi Anda tetap responsif, ikuti langkah-langkah berikut:

Menggunakan library Grpc.Core untuk framework UI lama

Jika Anda mengembangkan aplikasi yang menargetkan .NET Framework dan menggunakan teknologi UI lama seperti ASP.NET Web Forms atau WinForms, Anda dapat mengaktifkan library transportasi Grpc.Core lama sebagai berikut:

GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);

Menggunakan metode asinkron

Anda dapat menggunakan metode asinkron agar aplikasi Anda tetap responsif. Berikut beberapa contohnya.

Mengambil daftar kampanye dan mengisi 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}");
    }
}

Memperbarui anggaran kampanye dan menampilkan peringatan kotak pesan

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}");
    }
}