การใช้งานพื้นฐาน

การใช้งานไลบรารีของไคลเอ็นต์ขั้นพื้นฐานมีดังนี้


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

สร้างอินสแตนซ์ GoogleAdsClient

คลาสที่สำคัญที่สุดในไลบรารี .NET ของ Google Ads API คือคลาส GoogleAdsClient ซึ่งช่วยให้คุณสร้างคลาสบริการที่กำหนดค่าล่วงหน้าซึ่ง ใช้ในการเรียก API ได้ หากต้องการกำหนดค่าออบเจ็กต์ GoogleAdsClient คุณต้องสร้างออบเจ็กต์ GoogleAdsConfig และตั้งค่าที่จำเป็น โปรดดูข้อมูลเพิ่มเติมในคู่มือการกำหนดค่า


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

สร้างบริการ

GoogleAdsClient มีGetServiceวิธีที่ใช้สร้างบริการโฆษณาได้

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

เรามีคลาส Services ที่แสดงรายการ API และบริการที่รองรับทั้งหมด GetService เมธอดจะยอมรับออบเจ็กต์การแจงนับเหล่านี้เป็นอาร์กิวเมนต์ เมื่อสร้างบริการ เช่น หากต้องการสร้างอินสแตนซ์ของ CampaignServiceClient สำหรับ Google Ads API เวอร์ชัน V21 คุณต้องเรียกใช้เมธอด GoogleAdsClient.GetService โดยมี Services.V21.CampaignService เป็นอาร์กิวเมนต์ ดังที่แสดง ในตัวอย่างก่อนหน้า

การจัดการข้อผิดพลาด

การเรียก API ไม่ได้สำเร็จทุกครั้ง เซิร์ฟเวอร์อาจแสดงข้อผิดพลาดหากการเรียก API ล้มเหลวด้วยเหตุผลบางประการ คุณควรบันทึกข้อผิดพลาดของ API และจัดการข้อผิดพลาดเหล่านั้น อย่างเหมาะสม

ระบบจะส่ง GoogleAdsException เมื่อเกิดข้อผิดพลาดของ API โดยมี รายละเอียดที่จะช่วยให้คุณทราบว่าเกิดข้อผิดพลาดใดขึ้น

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

ความปลอดภัยของเธรด

การแชร์อินสแตนซ์ GoogleAdsClient ระหว่างหลายเธรดไม่ปลอดภัย เนื่องจากการเปลี่ยนแปลงการกำหนดค่าที่คุณทำในอินสแตนซ์ในเธรดหนึ่งอาจ ส่งผลต่อบริการที่คุณสร้างในเธรดอื่นๆ การดำเนินการต่างๆ เช่น การรับอินสแตนซ์บริการใหม่จากอินสแตนซ์ GoogleAdsClient และการโทรไปยังบริการหลายรายการพร้อมกันจะปลอดภัยต่อเธรด

แอปพลิเคชันแบบมัลติเธรดจะมีลักษณะดังนี้

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

ทำให้แอปพลิเคชันตอบสนองได้ดี

การเรียกเมธอด API ของ Google Ads API อาจใช้เวลาสักครู่จึงจะเสร็จสมบูรณ์ ทั้งนี้ขึ้นอยู่กับขนาดของคำขอ เราขอแนะนำให้ทำตามขั้นตอนต่อไปนี้เพื่อให้แอปพลิเคชันตอบสนองได้ดี

ใช้ไลบรารี Grpc.Core

หากคุณกำลังพัฒนาแอปพลิเคชันที่กำหนดเป้าหมายเป็น .NET Framework และใช้เทคโนโลยีเดิม เช่น ASP.NET Web Forms หรือแอปพลิเคชัน WinForms เราขอแนะนำให้ใช้ไลบรารี Grpc.Core เดิมดังนี้

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