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

في ما يلي الاستخدام الأساسي لمكتبة برامج ‎ .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 التي تُعدّد جميع إصدارات واجهة برمجة التطبيقات المتوافقة (حيث تستخدم الإصدارات الثانوية، مثل v26.1، تعداد الإصدار الرئيسي Services.V26) والخدمات. يقبل الإجراء 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}");
    }
}