في ما يلي الاستخدام الأساسي لمكتبة البرامج:
// 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
. تتيح لك إنشاء فئة خدمة مضبوطة مسبقًا يمكن استخدامها لإجراء طلبات من واجهة برمجة التطبيقات. لضبط إعدادات عنصر 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
يمكن استخدامها لإنشاء خدمة "إعلانات Google".
CampaignServiceClient campaignService = client.GetService(
Services.V21.CampaignService);
// Now make calls to CampaignService.
نوفّر الفئة Services
التي تسرد جميع إصدارات واجهة برمجة التطبيقات والخدمات المتوافقة. تقبل الطريقة GetService
عناصر التعداد هذه كمعلَمة
عند إنشاء الخدمة. على سبيل المثال، لإنشاء مثيل من
CampaignServiceClient
للإصدار V21
من Google Ads API،
عليك استدعاء الطريقة GoogleAdsClient.GetService
مع
Services.V21.CampaignService
كمعلَمة، كما هو موضّح
في المثال السابق.
معالجة الأخطاء
لن تنجح كل طلبات البيانات من واجهة برمجة التطبيقات. يمكن أن يعرض الخادم أخطاءً إذا تعذّرت معالجة طلبات البيانات من واجهة برمجة التطبيقات لسبب ما. من المهم تسجيل أخطاء واجهة برمجة التطبيقات والتعامل معها بشكل مناسب.
يتم عرض مثيل GoogleAdsException
عند حدوث خطأ في واجهة برمجة التطبيقات. ويتضمّن تفاصيل لمساعدتك في معرفة المشكلة التي حدثت:
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.
...
}
الحفاظ على استجابة تطبيقك
قد تستغرق عمليات طلب البيانات من واجهة 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);
}
```