Cách dùng cơ bản

Sau đây là cách sử dụng cơ bản của thư viện ứng dụng:


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

Tạo một thực thể GoogleAdsClient

Các lớp quan trọng nhất trong thư viện .NET của Google Ads API là lớp GoogleAdsClient. Nó cho phép bạn tạo một lớp dịch vụ được định cấu hình sẵn mà bạn có thể dùng để thực hiện các lệnh gọi API. Để định cấu hình một đối tượng GoogleAdsClient, bạn cần tạo một đối tượng GoogleAdsConfig và đặt các chế độ cài đặt cần thiết. Hãy tham khảo Hướng dẫn định cấu hình để tìm hiểu thêm.


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

Tạo một dịch vụ

GoogleAdsClient cung cấp một phương thức GetService có thể dùng để tạo một dịch vụ Quảng cáo.

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

Chúng tôi cung cấp một lớp Services liệt kê tất cả các phiên bản và dịch vụ API được hỗ trợ. Phương thức GetService chấp nhận các đối tượng liệt kê này làm đối số khi tạo dịch vụ. Ví dụ: để tạo một phiên bản của CampaignServiceClient cho phiên bản V21 của Google Ads API, bạn cần gọi phương thức GoogleAdsClient.GetService bằng Services.V21.CampaignService làm đối số, như trong ví dụ trước.

Xử lý lỗi

Không phải lệnh gọi API nào cũng thành công. Máy chủ có thể gửi lỗi nếu lệnh gọi API của bạn không thành công vì lý do nào đó. Bạn cần nắm bắt và xử lý các lỗi API một cách thích hợp.

Một thực thể GoogleAdsException sẽ được gửi khi xảy ra lỗi API. Thông báo này có thông tin chi tiết để giúp bạn xác định vấn đề:

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

Độ an toàn cho chuỗi

Bạn không nên chia sẻ một thực thể GoogleAdsClient giữa nhiều luồng, vì những thay đổi về cấu hình mà bạn thực hiện trên một thực thể trong một luồng có thể ảnh hưởng đến các dịch vụ mà bạn tạo trên các luồng khác. Các thao tác như lấy các thực thể dịch vụ mới từ một thực thể GoogleAdsClient và thực hiện các lệnh gọi đến nhiều dịch vụ song song đều an toàn về luồng.

Một ứng dụng đa luồng sẽ có dạng như sau:

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

Duy trì khả năng phản hồi của ứng dụng

Các lệnh gọi phương thức API Google Ads API có thể mất một khoảng thời gian để hoàn tất, tuỳ thuộc vào quy mô của các yêu cầu. Để giữ cho ứng dụng của bạn luôn phản hồi, bạn nên làm theo các bước sau:

Sử dụng thư viện Grpc.Core

Nếu đang phát triển một ứng dụng nhắm đến .NET Framework và sử dụng một công nghệ cũ như ứng dụng ASP.NET Web Forms hoặc WinForms, bạn nên sử dụng thư viện Grpc.Core cũ như sau:

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