Podstawowe użycie biblioteki klienta wygląda tak:
// 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.
Tworzenie instancji GoogleAdsClient
Najważniejszą klasą w bibliotece .NET interfejsu Google Ads API jest klasa GoogleAdsClient. Umożliwia ona utworzenie wstępnie skonfigurowanej klasy usługi, której można używać do wywoływania interfejsu API. Aby skonfigurować obiekt GoogleAdsClient, musisz utworzyć obiekt GoogleAdsConfig i ustawić niezbędne ustawienia. Więcej informacji znajdziesz w przewodniku po konfiguracji.
// 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 = ******;
Tworzenie usługi
GoogleAdsClient udostępnia metodę GetService, której można użyć do utworzenia usługi Ads.
CampaignServiceClient campaignService = client.GetService(
Services.V25.CampaignService);
// Now make calls to CampaignService.
Udostępniamy klasę Services, która zawiera listę wszystkich obsługiwanych wersji i usług interfejsu API. Podczas tworzenia usługi metoda GetService przyjmuje te obiekty wyliczeniowe jako argument. Aby na przykład utworzyć instancję
CampaignServiceClient dla wersji V25 interfejsu Google Ads API,
musisz wywołać metodę GoogleAdsClient.GetService z argumentem
Services.V25.CampaignService, jak pokazano
w poprzednim przykładzie.
Obsługa błędów
Nie każde wywołanie interfejsu API zakończy się powodzeniem. Jeśli wywołania interfejsu API nie powiodą się z jakiegoś powodu, serwer może zgłosić błędy. Ważne jest, aby przechwytywać błędy interfejsu API i odpowiednio je obsługiwać.
Gdy wystąpi błąd interfejsu API, zgłaszana jest instancja GoogleAdsException. Zawiera ona szczegóły, które pomogą Ci ustalić, co poszło nie tak:
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; } }
Bezpieczeństwo wątków
Nie można bezpiecznie udostępniać instancji GoogleAdsClient między wieloma wątkami, ponieważ zmiany konfiguracji wprowadzane w instancji w jednym wątku mogą wpływać na usługi tworzone w innych wątkach. Operacje takie jak uzyskiwanie nowych instancji usługi z instancji GoogleAdsClient i równoległe wywoływanie wielu usług są bezpieczne dla wątków.
Aplikacja wielowątkowa będzie wyglądać mniej więcej tak:
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.
...
}
Utrzymanie responsywności aplikacji
Wywołania metod interfejsu Google Ads API mogą potrwać dłużej, w zależności od rozmiaru żądań. Aby utrzymać responsywność aplikacji, zalecamy wykonanie tych czynności:
Używanie biblioteki Grpc.Core
Jeśli tworzysz aplikację, która jest przeznaczona dla .NET Framework i korzysta ze starszej technologii, takiej jak ASP.NET Web Forms lub aplikacja WinForms, zalecamy użycie starszej biblioteki Grpc.Core w ten sposób:
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);
}
```