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

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

// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
    OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
    OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
    LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};

// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);

// Create the required service.
CampaignServiceClient campaignService =
    client.GetService(Services.V26.CampaignService);

// Make calls to the service client.

เริ่มต้นไคลเอ็นต์และบริการ

หากต้องการโต้ตอบกับ Google Ads API ก่อนอื่นให้กำหนดค่าและสร้างอินสแตนซ์ GoogleAdsClient แล้วใช้เพื่อสร้างไคลเอ็นต์บริการ API เฉพาะที่คุณต้องการ

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

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

// Initialize a GoogleAdsConfig instance.
GoogleAdsConfig config = new GoogleAdsConfig()
{
    OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
    OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
    LoginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"
};

// Initialize a GoogleAdsClient instance.
GoogleAdsClient client = new GoogleAdsClient(config);

// Modify the GoogleAdsClient configuration afterwards if needed.
client.Config.LoginCustomerId = "INSERT_UPDATED_LOGIN_CUSTOMER_ID_HERE";

สร้างบริการ

GoogleAdsClient มีเมธอด GetService ที่ใช้สร้างไคลเอ็นต์บริการ API ได้

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

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

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

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

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

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V26.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 แยกกันสำหรับงานหรือเธรดของ Worker แต่ละรายการ

GoogleAdsClient client1 = new GoogleAdsClient();
GoogleAdsClient client2 = new GoogleAdsClient();

Task task1 = Task.Run(() => AddAdGroups(client1));
Task task2 = Task.Run(() => AddAdGroups(client2));

await Task.WhenAll(task1, task2);

public void AddAdGroups(GoogleAdsClient client)
{
    // Perform operations with client.
}

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

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

ใช้ไลบรารี Grpc.Core สำหรับเฟรมเวิร์ก UI แบบเดิม

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

GoogleAdsConfig config = new GoogleAdsConfig();
config.UseGrpcCore = true;
GoogleAdsClient client = new GoogleAdsClient(config);

ใช้เมธอดแบบไม่พร้อมกัน

คุณสามารถใช้เมธอดแบบอะซิงโครนัสเพื่อให้แอปพลิเคชันตอบสนอง ตัวอย่างเช่น

ดึงข้อมูลรายการแคมเปญและป้อนข้อมูลใน ListView

private async void OnRetrieveCampaignsButtonClick(object sender, EventArgs e)
{
    try
    {
        // Get the GoogleAdsService.
        GoogleAdsServiceClient googleAdsService = client.GetService(
            Services.V26.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>();
        await googleAdsService.SearchStreamAsync(
            customerId.ToString(),
            query,
            (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);
                }
            }
        );
        listView1.Items.AddRange(items.ToArray());
    }
    catch (GoogleAdsException ex)
    {
        MessageBox.Show($"API Error: {ex.Message}");
    }
}

อัปเดตงบประมาณแคมเปญและแสดงการแจ้งเตือนกล่องข้อความ

private async void OnUpdateBudgetButtonClick(object sender, EventArgs e)
{
    try
    {
        // Get the CampaignBudgetService.
        CampaignBudgetServiceClient budgetService = client.GetService(
            Services.V26.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 asynchronously.
        MutateCampaignBudgetsResponse response =
            await budgetService.MutateCampaignBudgetsAsync(
                customerId.ToString(),
                new CampaignBudgetOperation[] { budgetOperation });

        MessageBox.Show(response.Results[0].ResourceName);
    }
    catch (GoogleAdsException ex)
    {
        MessageBox.Show($"API Error: {ex.Message}");
    }
}