基本的な使い方

.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.V25.CampaignService);

// Make calls to the service client.

クライアントとサービスを初期化する

Google Ads API を操作するには、まず GoogleAdsClient を構成してインスタンス化し、それを使用して必要な特定の API サービス クライアントを作成します。

GoogleAdsClient インスタンスを作成する

Google Ads API .NET ライブラリで最も重要なクラスは 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 には、API サービス クライアントの作成に使用できる GetService メソッドが用意されています。

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

このライブラリは、サポートされているすべての API バージョン(v25.1 などのマイナー リリースでは、メジャー バージョンの列挙型 Services.V25 を使用)とサービスを列挙する Services クラスを提供します。GetService メソッドは、サービスを作成するときにこれらの列挙オブジェクトを引数として受け取ります。たとえば、Google Ads API のバージョン V25 の CampaignServiceClient のインスタンスを作成するには、前の例に示すように、引数として Services.V25.CampaignService を指定して GoogleAdsClient.GetService メソッドを呼び出します。

エラー処理

すべての API 呼び出しが成功するとは限りません。API 呼び出しがなんらかの理由で失敗した場合、サーバーはエラーを返すことがあります。API エラーをキャプチャして適切に処理することが重要です。

API エラーが発生すると、GoogleAdsException インスタンスがスローされます。エラーの原因を特定するのに役立つ詳細情報が含まれています。

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

スレッドの安全性

複数のスレッド間で共有される GoogleAdsClient インスタンスの構成状態を変更することは、スレッドセーフではありません。あるスレッドのインスタンスで行った構成の変更が、他のスレッドで作成したサービスに影響する可能性があるためです。ただし、変更されない GoogleAdsClient インスタンスから新しいサービス インスタンスを取得するなどの読み取り専用オペレーションや、複数のサービスへの呼び出しを並行して行うオペレーションはスレッドセーフです。

スレッドごとの構成変更を分離するには、ワーカー タスクまたはスレッドごとに個別の GoogleAdsClient をインスタンス化します。

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

アプリケーションの応答性を維持する

Google Ads API メソッド呼び出しは、リクエストのサイズによっては完了までに時間がかかることがあります。アプリケーションの応答性を維持するには、次の手順に沿って操作します。

以前の UI フレームワークに Grpc.Core ライブラリを使用する

.NET Framework を対象とし、ASP.NET Web フォームや WinForms などの以前の UI テクノロジーを使用するアプリケーションを開発している場合は、次のように以前の 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.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}");
    }
}

キャンペーンの予算を更新し、メッセージ ボックスのアラートを表示する

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