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

في ما يلي الاستخدام الأساسي لمكتبة برامج .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.V25.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.V25.CampaignService);
// Now make calls to CampaignService.

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

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

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

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

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V25.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.V25.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.V25.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}");
    }
}