基本用法

用戶端程式庫的基本用法如下:


// 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.V21.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 方法,可用於建立 Google Ads 服務。

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

我們提供 Services 類別,列舉所有支援的 API 版本和服務。建立服務時,GetService 方法會將這些列舉物件做為引數。舉例來說,如要為 Google Ads API 的 V21 版本建立 CampaignServiceClient 執行個體,您需要呼叫 GoogleAdsClient.GetService 方法,並以 Services.V21.CampaignService 做為引數,如上一個範例所示。

處理錯誤

並非每次 API 呼叫都會成功。如果 API 呼叫因故失敗,伺服器可能會擲回錯誤。請務必擷取 API 錯誤並妥善處理。

發生 API 錯誤時,系統會擲回 GoogleAdsException 例項。這份報告包含詳細資料,可協助您找出問題原因:

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V21.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 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 方法呼叫可能需要一段時間才能完成。為確保應用程式保持回應狀態,建議您採取下列步驟:

使用 Grpc.Core 程式庫

如果您要開發以 .NET Framework 為目標的應用程式,並使用 ASP.NET Web Forms 或 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.V21.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.V21.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);
}
```