Uso básico

El uso básico de la biblioteca cliente es el siguiente:


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

Crear una instancia de GoogleAdsClient

Las clases más importantes de la biblioteca de la API de Google Ads para .NET son las clases GoogleAdsClient. Te permite crear una clase de servicio preconfigurada que se puede usar para realizar llamadas a la API. Para configurar un objeto GoogleAdsClient, debes crear un objeto GoogleAdsConfig y establecer la configuración necesaria. Consulta la guía de configuración para obtener más información.


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

Crear un servicio

GoogleAdsClient proporciona un método GetService que se puede usar para crear un servicio de Ads.

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

Proporcionamos una clase Services que enumera todos los servicios y las versiones de API compatibles. El método GetService acepta estos objetos de enumeración como argumento cuando se crea el servicio. Por ejemplo, para crear una instancia de CampaignServiceClient para la versión V21 de la API de Google Ads, debes llamar al método GoogleAdsClient.GetService con Services.V21.CampaignService como argumento, como se muestra en el ejemplo anterior.

Manejo de errores

No todas las llamadas a la API se realizarán correctamente. El servidor puede arrojar errores si tus llamadas a la API fallan por algún motivo. Es importante capturar los errores de la API y controlarlos de manera adecuada.

Se arroja una instancia de GoogleAdsException cuando se produce un error de API. Tiene detalles que te ayudan a descubrir qué salió mal:

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

Seguridad del subproceso

No es seguro compartir una instancia de GoogleAdsClient entre varios subprocesos, ya que los cambios de configuración que realices en una instancia en un subproceso podrían afectar los servicios que crees en otros subprocesos. Las operaciones como la obtención de nuevas instancias de servicio desde una instancia de GoogleAdsClient y la realización de llamadas a varios servicios en paralelo son seguras para el subproceso.

Una aplicación de subprocesos múltiples se vería de la siguiente manera:

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

Mantén la capacidad de respuesta de tu aplicación

Las llamadas a los métodos de la API de la API de Google Ads pueden tardar un tiempo en completarse, según el tamaño de las solicitudes. Para que tu aplicación siga respondiendo, te recomendamos que sigas estos pasos:

Usa la biblioteca Grpc.Core

Si desarrollas una aplicación que se orienta a .NET Framework y usa una tecnología heredada, como una aplicación de ASP.NET Web Forms o WinForms, te recomendamos que uses la biblioteca Grpc.Core heredada de la siguiente manera:

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