Uso básico

O uso básico da biblioteca de cliente é o seguinte:


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

Criar uma instância GoogleAdsClient

As classes mais importantes na biblioteca .NET da API Google Ads são a GoogleAdsClient. Ele permite criar uma classe de serviço pré-configurada que pode ser usada para fazer chamadas de API. Para configurar um objeto GoogleAdsClient, você precisa criar um objeto GoogleAdsConfig e definir as configurações necessárias. Consulte o guia de configuração para saber mais.


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

Criar um serviço

GoogleAdsClient fornece um método GetService que pode ser usado para criar um serviço do Google Ads.

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

Oferecemos uma classe Services que enumera todas as versões e serviços de API compatíveis. O método GetService aceita esses objetos de enumeração como argumento ao criar o serviço. Por exemplo, para criar uma instância de CampaignServiceClient para a versão V21 da API Google Ads, chame o método GoogleAdsClient.GetService com Services.V21.CampaignService como argumento, conforme mostrado no exemplo anterior.

Tratamento de erros

Nem todas as chamadas de API são bem-sucedidas. O servidor pode gerar erros se as chamadas de API falharem por algum motivo. É importante capturar erros de API e processá-los de maneira adequada.

Uma instância GoogleAdsException é gerada quando ocorre um erro na API. Ele tem detalhes para ajudar você a descobrir o que deu errado:

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

Segurança de linha de execução

Não é seguro compartilhar uma instância GoogleAdsClient entre várias linhas de execução, já que as mudanças de configuração feitas em uma instância em uma linha de execução podem afetar os serviços criados em outras linhas de execução. Operações como obter novas instâncias de serviço de uma instância GoogleAdsClient e fazer chamadas para vários serviços em paralelo são seguras para linhas de execução.

Um aplicativo multithreaded seria parecido com isto:

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

Manter seu aplicativo responsivo

As chamadas de método da API Google Ads podem levar um tempo para serem concluídas, dependendo do tamanho das solicitações. Para manter a capacidade de resposta do aplicativo, recomendamos as seguintes etapas:

Usar a biblioteca Grpc.Core

Se você estiver desenvolvendo um aplicativo voltado para o .NET Framework e usando uma tecnologia legada, como o ASP.NET Web Forms ou um aplicativo WinForms, recomendamos usar a biblioteca legada Grpc.Core da seguinte maneira:

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