الاستخدام الأساسي

في ما يلي الاستخدام الأساسي لمكتبة عملاء ‎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 وإنشاؤه، ثم استخدامه لإنشاء عملاء خدمة واجهة برمجة التطبيقات المحدّدين التي تحتاج إليها.

إنشاء مثيل GoogleAdsClient

الفئة الأهم في مكتبة ‎NET لـ Google Ads API هي فئة GoogleAdsClient. تتيح لك هذه الفئة إنشاء عميل خدمة تم ضبطه مسبقًا ويمكن استخدامه لإجراء طلبات بيانات من واجهة برمجة التطبيقات. لضبط عنصر 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 يمكن استخدامها لإنشاء عميل خدمة واجهة برمجة التطبيقات.

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

توفر المكتبة فئة Services تسرد جميع إصدارات واجهة برمجة التطبيقات والخدمات المتوافقة (حيث تستخدم الإصدارات الثانوية، مثل v25.1، تعداد رقم الإصدار الرئيسي، Services.V25). تقبل طريقة GetService عناصر التعداد هذه كحجّة عند إنشاء الخدمة. على سبيل المثال، لإنشاء مثيل من CampaignServiceClient للإصدار V26 من Google Ads API، استدعِ طريقة GoogleAdsClient.GetService مع Services.V26.CampaignService كحجّة، كما هو موضّح في المثال السابق.

معالجة الأخطاء

لا تنجح جميع طلبات البيانات من واجهة برمجة التطبيقات. يمكن أن يعرض الخادم أخطاءً إذا تعذّر تنفيذ طلبات البيانات من واجهة برمجة التطبيقات لسبب ما. من المهم رصد أخطاء واجهة برمجة التطبيقات ومعالجتها بشكل مناسب.

يتم طرح مثيل GoogleAdsException عند حدوث خطأ في واجهة برمجة التطبيقات. يحتوي هذا المثيل على تفاصيل تساعدك في تحديد المشكلة:

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 لكل مهمة أو سلسلة محادثات عاملة:

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 لأُطر واجهة المستخدم القديمة

إذا كنت تطوّر تطبيقًا يستهدف ‎NET Framework ويستخدم تكنولوجيا واجهة مستخدم قديمة، مثل 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}");
    }
}