.NET 클라이언트 라이브러리의 기본 사용법은 다음과 같습니다.
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Create the required service.
CampaignServiceClient campaignService =
client.GetService(Services.V25.CampaignService);
// Make calls to the service client.
클라이언트 및 서비스 초기화
Google Ads API와 상호작용하려면 먼저 GoogleAdsClient를 구성하고 인스턴스화한 다음 이를 사용하여 필요한 특정 API 서비스 클라이언트를 만듭니다.
GoogleAdsClient 인스턴스 만들기
Google Ads API .NET 라이브러리에서 가장 중요한 클래스는 GoogleAdsClient 클래스입니다. API 호출에 사용할 수 있는 사전 구성된 서비스 클라이언트를 만들 수 있습니다. GoogleAdsClient 객체를 구성하려면 GoogleAdsConfig 객체를 만들고 필요한 속성을 설정합니다. 자세한 내용은 구성 가이드를 참고하세요.
// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};
// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);
// Modify the GoogleAdsClient configuration afterwards if needed.
client.Config.LoginCustomerId = "INSERT_UPDATED_LOGIN_CUSTOMER_ID_HERE";
서비스 만들기
GoogleAdsClient는 API 서비스 클라이언트를 만드는 데 사용할 수 있는 GetService 메서드를 제공합니다.
CampaignServiceClient campaignService = client.GetService(
Services.V25.CampaignService);
// Now make calls to CampaignService.
이 라이브러리는 지원되는 모든 API 버전을 열거하는 Services 클래스 (v25.1과 같은 부 버전은 메이저 버전 열거형 Services.V25 사용)와 서비스를 제공합니다. 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를 인스턴스화하세요.
GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();
Task task1 = Task.Run(() => AddAdGroups(client1));
Task task2 = Task.Run(() => AddAdGroups(client2));
await Task.WhenAll(task1, task2);
public void AddAdGroups(GoogleAdsClient client)
{
// Perform operations with client.
}
애플리케이션의 응답성 유지
요청 크기에 따라 Google Ads API 메서드 호출을 완료하는 데 시간이 걸릴 수 있습니다. 애플리케이션의 응답성을 유지하려면 다음 단계를 따르세요.
기존 UI 프레임워크에 Grpc.Core 라이브러리 사용
.NET Framework를 타겟팅하고 ASP.NET Web Forms 또는 WinForms와 같은 기존 UI 기술을 사용하는 애플리케이션을 개발하는 경우 다음과 같이 기존 Grpc.Core 전송 라이브러리를 사용 설정할 수 있습니다.
GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);
비동기 메서드 사용
비동기 메서드를 사용하여 애플리케이션의 응답성을 유지할 수 있습니다. 다음은 몇 가지 예입니다.
캠페인 목록을 가져와 ListView를 채웁니다.
private async void OnRetrieveCampaignsButtonClick(object sender, EventArgs e)
{
try
{
// 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>();
await googleAdsService.SearchStreamAsync(
customerId.ToString(),
query,
(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);
}
}
);
listView1.Items.AddRange(items.ToArray());
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}
캠페인 예산을 업데이트하고 메시지 상자 알림을 표시합니다.
private async void OnUpdateBudgetButtonClick(object sender, EventArgs e)
{
try
{
// Get the CampaignBudgetService.
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 asynchronously.
MutateCampaignBudgetsResponse response =
await budgetService.MutateCampaignBudgetsAsync(
customerId.ToString(),
new CampaignBudgetOperation[] { budgetOperation });
MessageBox.Show(response.Results[0].ResourceName);
}
catch (GoogleAdsException ex)
{
MessageBox.Show($"API Error: {ex.Message}");
}
}