Основное использование клиентской библиотеки следующее:
// 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
, который можно использовать для создания службы Ads.
CampaignServiceClient campaignService = client.GetService(
Services.V21.CampaignService);
// Now make calls to CampaignService.
Мы предоставляем класс Services
, который перечисляет все поддерживаемые версии API и сервисы. Метод GetService
принимает эти объекты перечисления в качестве аргумента при создании сервиса. Например, чтобы создать экземпляр CampaignServiceClient
для версии V21
API Google Ads, необходимо вызвать метод 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.
...
}
Сохраняйте ваше приложение адаптивным
Вызовы методов API 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);
}
```