Utilisation de base

L'utilisation de base de la bibliothèque cliente est la suivante :


// 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.

Créer une instance GoogleAdsClient

La classe GoogleAdsClient est la plus importante de la bibliothèque .NET de l'API Google Ads. Il vous permet de créer une classe de service préconfigurée qui peut être utilisée pour effectuer des appels d'API. Pour configurer un objet GoogleAdsClient, vous devez créer un objet GoogleAdsConfig et définir les paramètres nécessaires. Pour en savoir plus, consultez le guide de configuration.


// 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 = ******;

Créer un service

GoogleAdsClient fournit une méthode GetService qui peut être utilisée pour créer un service Ads.

CampaignServiceClient campaignService = client.GetService(
    Services.V21.CampaignService);
// Now make calls to CampaignService.

Nous fournissons une classe Services qui énumère toutes les versions et tous les services d'API compatibles. La méthode GetService accepte ces objets d'énumération comme argument lors de la création du service. Par exemple, pour créer une instance de CampaignServiceClient pour la version V21 de l'API Google Ads, vous devez appeler la méthode GoogleAdsClient.GetService avec Services.V21.CampaignService comme argument, comme indiqué dans l'exemple précédent.

Gestion des exceptions

Tous les appels d'API ne sont pas forcément réussis. Le serveur peut générer des erreurs si vos appels d'API échouent pour une raison quelconque. Il est important de capturer les erreurs d'API et de les gérer de manière appropriée.

Une instance GoogleAdsException est générée lorsqu'une erreur d'API se produit. Il contient des informations qui vous aideront à comprendre ce qui s'est passé :

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;
    }
}
      

Thread safety

Il n'est pas sûr de partager une instance GoogleAdsClient entre plusieurs threads, car les modifications de configuration que vous apportez à une instance dans un thread peuvent affecter les services que vous créez sur d'autres threads. Les opérations telles que l'obtention de nouvelles instances de service à partir d'une instance GoogleAdsClient et l'appel de plusieurs services en parallèle sont thread-safe.

Une application multithread ressemblerait à ceci :

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.
  ...
}

Préserver la réactivité de votre application

Les appels de méthode de l'API Google Ads peuvent prendre un certain temps, selon la taille des requêtes. Pour que votre application reste réactive, nous vous recommandons de procéder comme suit :

Utiliser la bibliothèque Grpc.Core

Si vous développez une application qui cible .NET Framework et utilise une technologie ancienne telle qu'ASP.NET Web Forms ou une application WinForms, nous vous recommandons d'utiliser l'ancienne bibliothèque Grpc.Core comme suit :

   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);
}
```