Utilizzo di base

L'utilizzo di base della libreria client è il seguente:


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

Crea un'istanza GoogleAdsClient

Le classi più importanti nella libreria .NET dell'API Google Ads sono le classi GoogleAdsClient. Consente di creare una classe di servizio preconfigurata che può essere utilizzata per effettuare chiamate API. Per configurare un oggetto GoogleAdsClient, devi creare un oggetto GoogleAdsConfig e impostare le impostazioni necessarie. Per scoprire di più, consulta la guida alla configurazione.


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

Crea un servizio

GoogleAdsClient fornisce un metodo GetService che può essere utilizzato per creare un servizio Google Ads.

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

Forniamo una classe Services che enumera tutti i servizi e le versioni dell'API supportati. Il metodo GetService accetta questi oggetti di enumerazione come argomento durante la creazione del servizio. Ad esempio, per creare un'istanza di CampaignServiceClient per la versione V21 dell'API Google Ads, devi chiamare il metodo GoogleAdsClient.GetService con Services.V21.CampaignService come argomento, come mostrato nell'esempio precedente.

Gestione degli errori

Non tutte le chiamate API andranno a buon fine. Il server può generare errori se le chiamate API non vanno a buon fine per qualche motivo. È importante acquisire gli errori API e gestirli in modo appropriato.

Viene generata un'istanza di GoogleAdsException quando si verifica un errore API. Contiene dettagli per aiutarti a capire cosa è andato storto:

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

Non è sicuro condividere un'istanza GoogleAdsClient tra più thread, poiché le modifiche alla configurazione apportate a un'istanza in un thread potrebbero influire sui servizi creati in altri thread. Operazioni come l'ottenimento di nuove istanze di servizio da un'istanza GoogleAdsClient e l'esecuzione di chiamate a più servizi in parallelo sono thread-safe.

Un'applicazione multithread avrebbe un aspetto simile a questo:

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

Mantenere la reattività dell'applicazione

Il completamento delle chiamate al metodo API dell'API Google Ads potrebbe richiedere un po' di tempo, a seconda delle dimensioni delle richieste. Per mantenere la reattività dell'applicazione, ti consigliamo di seguire questi passaggi:

Utilizzare la libreria Grpc.Core

Se stai sviluppando un'applicazione che ha come target .NET Framework e utilizza una tecnologia legacy come ASP.NET Web Forms o un'applicazione WinForms, ti consigliamo di utilizzare la libreria legacy Grpc.Core nel seguente modo:

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