클라이언트 라이브러리의 기본 사용법은 다음과 같습니다.
// 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
메서드를 제공합니다.
CampaignServiceClient campaignService = client.GetService(
Services.V21.CampaignService);
// Now make calls to CampaignService.
지원되는 모든 API 버전과 서비스를 열거하는 Services
클래스를 제공합니다. GetService
메서드는 서비스를 만들 때 이러한 열거 객체를 인수로 허용합니다. 예를 들어 Google Ads API의 V21
버전에 대한 CampaignServiceClient
인스턴스를 만들려면 이전 예와 같이 Services.V21.CampaignService
를 인수로 사용하여 GoogleAdsClient.GetService
메서드를 호출해야 합니다.
오류 처리
모든 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 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);
}
```