客户端库的基本用法如下:
// 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.V25.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.V25.CampaignService);
// Now make calls to CampaignService.
我们提供了一个 Services 类,用于枚举所有受支持的 API 版本和服务。创建服务时,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 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 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.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>();
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.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.
Task<MutateCampaignBudgetsResponse> t = budgetService.MutateCampaignBudgetsAsync(
customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
await t;
MutateCampaignBudgetsResponse response = t.Result;
MessageBox.Show(response.Results[0].ResourceName);
}
```