کاربرد اصلی کتابخانه کلاینت به شرح زیر است:
// 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.V22.CampaignService);
// Make more calls to service class.
یک نمونه GoogleAdsClient
ایجاد کنید
مهمترین کلاسها در کتابخانه Google Ads API .NET، کلاس GoogleAdsClient
است. این کلاس به شما امکان میدهد یک کلاس سرویس از پیش پیکربندیشده ایجاد کنید که میتواند برای فراخوانیهای API استفاده شود. برای پیکربندی یک شیء 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
ارائه میدهد که میتواند برای ایجاد یک سرویس تبلیغات استفاده شود.
CampaignServiceClient campaignService = client.GetService(
Services.V22.CampaignService);
// Now make calls to CampaignService.
ما یک کلاس Services
ارائه میدهیم که تمام نسخهها و سرویسهای API پشتیبانیشده را فهرست میکند. متد GetService
هنگام ایجاد سرویس، این اشیاء شمارشی را به عنوان آرگومان میپذیرد. برای مثال، برای ایجاد یک نمونه از CampaignServiceClient
برای نسخه V22
از API تبلیغات گوگل، باید متد GoogleAdsClient.GetService
را با Services.V22.CampaignService
به عنوان آرگومان فراخوانی کنید، همانطور که در مثال قبلی نشان داده شده است.
مدیریت خطا
هر فراخوانی API موفق نخواهد بود. اگر فراخوانیهای API شما به هر دلیلی با شکست مواجه شوند، سرور میتواند خطا صادر کند. مهم است که خطاهای API را ثبت کرده و به طور مناسب آنها را مدیریت کنید.
یک نمونه از GoogleAdsException
زمانی ایجاد میشود که یک خطای API رخ دهد. این نمونه شامل جزئیاتی است که به شما کمک میکند بفهمید چه چیزی اشتباه رخ داده است:
public void Run(GoogleAdsClient client, long customerId) { // Get the GoogleAdsService. GoogleAdsServiceClient googleAdsService = client.GetService( Services.V22.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
بین چندین thread امن نیست، زیرا تغییرات پیکربندی که روی یک نمونه در یک thread ایجاد میکنید ممکن است روی سرویسهایی که در threadهای دیگر ایجاد میکنید تأثیر بگذارد. عملیاتی مانند دریافت نمونههای سرویس جدید از یک نمونه GoogleAdsClient
و فراخوانی موازی چندین سرویس، thread-safe هستند.
یک برنامه چند رشتهای چیزی شبیه به این خواهد بود:
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.
...
}
اپلیکیشن خود را واکنشگرا نگه دارید
بسته به حجم درخواستها، فراخوانی متدهای API گوگل ادز ممکن است مدتی طول بکشد. برای اینکه برنامه شما واکنشگرا باشد، مراحل زیر را توصیه میکنیم:
از کتابخانه Grpc.Core
استفاده کنید
اگر در حال توسعه برنامهای هستید که چارچوب داتنت را هدف قرار میدهد و از فناوری قدیمی مانند 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.V22.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.V22.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);
}
```