クライアント ライブラリの基本的な使い方は次のとおりです。
// Initialize a GoogleAdsConfig class.
GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
    OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
    LoginCustomerId = ******
};
// Initialize a GoogleAdsClient class.
GoogleAdsClient client = new GoogleAdsClient(config);
// Create the required service.
CampaignServiceClient campaignService =
    client.GetService(Services.V22.CampaignService);
// Make more calls to service class.
GoogleAdsClient インスタンスを作成する
Google Ads API .NET ライブラリで最も重要なクラスは GoogleAdsClient クラスです。API 呼び出しに使用できる事前構成済みのサービス クラスを作成できます。GoogleAdsClient オブジェクトを構成するには、GoogleAdsConfig オブジェクトを作成し、必要な設定を行う必要があります。詳細については、構成ガイドをご覧ください。
// Initialize a GoogleAdsConfig class.
GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
    OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
    LoginCustomerId = ******
};
// Initialize a GoogleAdsClient class.
GoogleAdsClient client = new GoogleAdsClient(config);
// Modify the GoogleAdsClient afterwards.
client.Config.LoginCustomerId = ******;
サービスの作成
GoogleAdsClient は、広告サービスを作成するために使用できる GetService メソッドを提供します。
CampaignServiceClient campaignService = client.GetService(
    Services.V22.CampaignService);
// Now make calls to CampaignService.
サポートされているすべての API バージョンとサービスを列挙する Services クラスを提供します。GetService メソッドは、サービスを作成するときにこれらの列挙オブジェクトを引数として受け取ります。たとえば、Google Ads API のバージョン V22 の CampaignServiceClient のインスタンスを作成するには、前の例に示すように、引数として Services.V22.CampaignService を指定して GoogleAdsClient.GetService メソッドを呼び出す必要があります。
エラー処理
すべての API 呼び出しが成功するとは限りません。API 呼び出しがなんらかの理由で失敗した場合、サーバーはエラーをスローする可能性があります。API エラーをキャプチャして適切に処理することが重要です。
API エラーが発生すると、GoogleAdsException インスタンスがスローされます。問題の原因を特定するのに役立つ詳細情報が含まれています。
public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V22.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; } }
スレッドの安全性
1 つのスレッドのインスタンスで行った構成変更が、他のスレッドで作成したサービスに影響する可能性があるため、複数のスレッド間で 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.
  ...
}
アプリケーションの応答性を維持する
Google Ads API の API メソッド呼び出しは、リクエストのサイズによっては完了に時間がかかることがあります。アプリケーションの応答性を維持するには、次の手順をおすすめします。
Grpc.Core ライブラリを使用する
.NET Framework を対象とし、ASP.NET Web フォームや WinForms アプリケーションなどのレガシー テクノロジーを使用するアプリケーションを開発する場合は、次のようにレガシー Grpc.Core ライブラリを使用することをおすすめします。
   GoogleAdsConfig config = new GoogleAdsConfig();
   config.UseGrpcCore = true;
   GoogleAdsClient client = new GoogleAdsClient(config);
   ```
### Use the asynchronous methods {: #asynchronous}
You can use asynchronous methods to keep your application responsive. Here are a
couple of examples.
#### Retrieve the list of campaigns, and populate a `ListView`
```c#
private async void button1_Click(object sender, EventArgs e)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V22.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>();
    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());
}
```
#### Update a campaign budget and display a Message box alert
```c#
private async void button2_Click(object sender, EventArgs e)
{
    // Get the BudgetService.
    CampaignBudgetServiceClient budgetService = client.GetService(
        Services.V22.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<MutateCampaignBudgetsResponse> t = budgetService.MutateCampaignBudgetsAsync(
        customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
    await t;
    MutateCampaignBudgetsResponse response = t.Result;
    MessageBox.Show(response.Results[0].ResourceName);
}
```