Export (0) Print
Expand All

Getting Started Using C# with Bing Ads Services

System_CLiX_note Note

Currently the Bing Ads .NET SDK Version 9.3 is available in Beta.

To get started developing Bing Ads applications with a .NET language, install the SDK and either download the examples or follow one of the application walkthroughs for a web or desktop application. The examples within C# Examples for Bing Ads have been developed with the Bing Ads .NET SDK in the environment described below. Your custom configuration may vary.

Setting Up the Development Environment

You need user credentials with access to Bing Ads either in production or sandbox. You also need a developer token. For more information, please see Getting Started With the Bing Ads API and Sandbox.

To authenticate with a Microsoft account in production, the Microsoft account user must sign up for a new Bing Ads account, be invited to manage your Bing Ads accounts, or be linked to an existing legacy Bing Ads username. You also must register an application and get the corresponding client identifier. You also need to take note of the client secret and redirect URI if you are developing a web application. For more information, see Managing User Authentication with OAuth.

To use the Bing Ads .NET SDK, you must install and use .NET Framework 4.5 or later. In Visual Studio go to the project Properties -> Application -> Target framework and make sure that .NET Framework 4.5 is selected.

The examples are developed and run with Visual Studio 2012. For information about installing Visual Studio, see Visual Studio Downloads.

Installing the SDK

Install the Bing Ads .NET SDK through NuGet, either through the Manage NuGet Packages user interface, or through the Package Manager Console. For information about installing NuGet, see http://docs.nuget.org.

System_CLiX_note Note

The NuGet installation includes the following required libraries.

Manage NuGet Packages

  1. Right-click on your Visual Studio project and select Manage NuGet Packages.

  2. Click the Online package category and search for Bing Ads SDK.

    System_CLiX_note Note

    Within Manage NuGet Packages you must select the Include Prerelease combo box value instead of Stable Only, since the SDK is currently available in Beta.

  3. Click the Install button for Bing Ads SDK.

Package Manager Console

  1. Click on Tools -> NuGet Package Manager -> Package Manager Console.

  2. Within the console command line, type Install-Package Microsoft.BingAds.SDK -Pre.

    System_CLiX_note Note

    The -Pre option indicates this is a pre-release package.

Walkthroughs

Once you have the Bing Ads .NET SDK installed, you can either view the C# Examples for Bing Ads, download the examples or follow one of the application walkthroughs for a web or desktop application.

Using OAuth

The OAuth classes in the client library abstract the low level user authorization details, so you can focus at a high level on your security requirements. The client library objects take care of low level details such as formatting the authorization and redirect URIs, setting the request headers, and parsing the redirect traffic and response stream.

For repeat or long term authentication, you should follow the authorization code grant flow for obtaining an access token. This is a standard OAuth 2.0 flow and is defined in detail in the Authorization Code Grant section of the OAuth 2.0 spec. The steps below describe the procedural workflow, and references code blocks from the Walkthrough: Bing Ads Web Application in C#. For more information both about authorization code and implicit grant flows, see Managing User Authentication with OAuth.

  1. Create an instance of OAuthWebAuthCodeGrant, that will be used to manage Microsoft Account user authorization. Replace ClientId, ClientSecret, and RedirectionUri with the values configured in Registering Your Application.

     var authorization = new OAuthWebAuthCodeGrant(ClientId, ClientSecret, new Uri(RedirectionUri));
    
  2. Request user consent by connecting to the Microsoft Account authorization endpoint through a web browser control. Call the GetAuthorizationEndpoint method of the OAuthWebAuthCodeGrant instance that you created in the earlier step.

    return Redirect(authorization.GetAuthorizationEndpoint().ToString());
    
    System_CLiX_noteNote

    The user will be prompted through the Microsoft Account authorization web browser control to grant permissions for your application to manage their Bing Ads accounts.

    The authorization service calls back to your application with the redirection URI, which includes an authorization code if the user authorized your application to manage their Bing Ads accounts. For example the callback Url includes an authorization code as follows if the user granted permissions for your application to manage their Bing Ads accounts: https://contoso.com/redirect/?code=AUTHORIZATION_CODE. If the user granted your application permissions to manage their Bing Ads accounts, you should use the AUTHORIZATION_CODE right away in the next step. The short duration of the authorization code, for example 5 minutes, is subject to change.

    If the user denied your application permissions to manage their Bing Ads accounts, the callback URI includes an error and error description field as follows: REDIRECTURI?error=access_denied&error_description=ERROR_DESCRIPTION.

  3. Use the authorization code to request the access token and refresh token. Pass the full callback Url to the RequestAccessAndRefreshTokensAsync method of your OAuthWebAuthCodeGrant instance. This method uses the authorization code fragment to request the access token and refresh token.

    if (Request["code"] != null)
    {
        await authorization.RequestAccessAndRefreshTokensAsync(Request.Url);
    }
    
    System_CLiX_noteNote

    If this step succeeded, your application has permissions to manage the user's Bing Ads accounts. To call Bing Ads services, you should initialize either ServiceClient<TService> or BulkServiceManager with AuthorizationData that contains your OAuthWebAuthCodeGrant instance.

    When calling Bing Ads services with ServiceClient<TService> or BulkServiceManager, each will refresh your access token automatically if they detect the AuthenticationTokenExpired (109) error code.

    For more information, see Using AuthorizationData, Using ServiceClient, and Using BulkServiceManager.

  4. Save the refresh token whenever new OAuth tokens are received by subscribing to the NewOAuthTokensReceived event handler.

    authorization.NewOAuthTokensReceived += 
        (sender, args) => SaveRefreshToken(args.NewRefreshToken);
    
    System_CLiX_noteNote

    You can also get the AccessToken, RefreshToken, and ExpiresIn values from the OAuthTokens property of your OAuthWebAuthCodeGrant instance. Call the RequestAccessAndRefreshTokensAsync method as shown in the previous step.

    Whereas the refresh token parameter does not have a defined expiration period, you should expect it to last several months. As a best practice the refresh token should be set to the value of the most recent refresh token retrieved.

    You may need to start again from Step 1 and request user consent if, for example the Microsoft Account user changed their password, removed a device from their list of trusted devices, or removed permissions for your application to authenticate on their behalf.

Using AuthorizationData

You must initialize a new instance of ServiceClient<TService> or BulkServiceManager with AuthorizationData. The class contains properties that Bing Ads uses to authorize a user. The ServiceClient<TService> and BulkServiceManager classes handle common request header fields for you, allowing to specify the Authentication, CustomerId, AccountId, and DeveloperToken properties in the AuthorizationData object once for each service. For more information, see Using ServiceClient and Using BulkServiceManager.

The following code block shows how to create an instance of AuthorizationData and set its Authentication, CustomerId, AccountId, and DeveloperToken properties.

var authorizationData = new AuthorizationData
{
    Authentication = <AuthenticationGoesHere>, 
    CustomerId = <CustomerIdGoesHere>,
    AccountId = <AccountIdGoesHere>,
    DeveloperToken = "<DeveloperTokenGoesHere>"
};

The Authentication property must be set to an Authentication-derived class such as OAuthWebAuthCodeGrant, OAuthDesktopMobileAuthCodeGrant, OAuthDesktopMobileImplicitGrant, or PasswordAuthentication. When ServiceClient<TService> or BulkServiceManager call Bing Ads services, they set the AuthenticationToken header element for each service request message to the value of the AccessToken property of your Authentication-derived instance. For more information, see Service Request Headers,Using ServiceClient and Using BulkServiceManager

Some services such as Customer Management do not accept CustomerId and CustomerAccountId headers, so they will be ignored if you specified them in the AuthorizationData object.

Using ServiceClient<TService>

You can use an instance of the ServiceClient<TService> class to call any methods in the service, where TService is one of the following client service interfaces:

  • IAdIntelligenceService

  • IBulkService

  • ICampaignManagementService

  • ICustomerBillingService

  • ICustomerManagementService

  • IOptimizerService

  • IReportingService

The ServiceClient<TService> class handles common request header fields for you, allowing to specify the Authentication, CustomerId, AccountId, and DeveloperToken properties in the AuthorizationData object once for each service. For more information, see Using AuthorizationData.

The primary method of the ServiceClient<TService> class is CallAsync. The method parameter is the delegate for the service operation that you want to call. The request parameter of this method must be a request message corresponding to the name of the service operation specified by the first request parameter. The request message must match the service operation that is specified as the delegate in the first request.

public TResponse CallAsync<TRequest, TResponse>(
    Func<TService, TRequest, TResponse> method,
    TRequest request
)

The header elements that the CallAsync method sets will differ depending on the type of authentication specified in AuthorizationData object and the requirements of the service. For example if you use one of the OAuth classes such as OAuthWebAuthCodeGrant, the AuthenticationToken will be set by CallAsync, whereas the UserName and Password headers will remain empty. If you use PasswordAuthentication, the UserName and Password headers will be set by CallAsync instead of AuthenticationToken.

In the following sample, the method delegate is (s, r) => s.GetUserAsync(r) which takes a GetUserRequest message as the request parameter (TRequest) and returns a GetUserResponse message (TResponse).

private async Task<User> GetUserAsync(long? userId)
{
    var request = new GetUserRequest
    {
        UserId = userId
    };

    return (await _customerService.CallAsync((s, r) => s.GetUserAsync(r), request)).User;
}
System_CLiX_noteNote

If you set the AuthenticationToken, CustomerId, AccountId, DeveloperToken, UserName, or Password header elements in this request parameter, they will be ignored. ServiceClient<TService> always uses the AuthorizationData provided with its initialization.

Using BulkServiceManager

Take advantage of the Bulk service to efficiently manage ads and keywords for all campaigns in an account. The client library provides classes to accelerate productivity for downloading and uploading entities. For example the DownloadFileAsync method of the BulkServiceManager class will submit your download request to the bulk service, poll the service until completed, and download the file to the local directory that you specified in the request. Use the BulkFileReader class instead of writing a file parser to read the download results. The BulkFileReader provides access to the bulk file records in BulkEntity derived classes, which contain the familiar Campaign Management data objects and value sets.

The BulkServiceManager class handles common request header fields for you, allowing to specify the Authentication, CustomerId, AccountId, and DeveloperToken properties in the AuthorizationData object once for each service. For more information, see Using AuthorizationData.

The client library supports the following scenarios.

Background Completion with BulkServiceManager

You can submit a download or upload request and the BulkServiceManager will automatically return results. The BulkServiceManager abstracts the details of checking for result file completion, and you don't have to write any code for results polling.

public async Task RunAsync(AuthorizationData authorizationData)
{
    BulkService = new BulkServiceManager(authorizationData);

    var progress = new Progress<BulkOperationProgressInfo>(x =>
        OutputStatusMessage(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture))));

    var downloadParameters = new DownloadParameters
    {
        CampaignIds = null,
        DataScope = DataScope.EntityData,
        Entities = BulkDownloadEntity.Keywords,
        FileType = DownloadFileType.Csv,
        LastSyncTimeInUTC = null,
        ResultFileDirectory = FileDirectory,
        ResultFileName = ResultFileName,
        OverwriteResultFile = true
    };

    // You may optionally cancel the download after a specified time interval. 
    // Pass this object to the DownloadFileAsync operation or specify CancellationToken.None. 

    var tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter(36000000);
    
    // Submit the download request, and the results file will be downloaded to the specified local file. 

    var resultFile = (await BulkService.DownloadFileAsync(downloadParameters, progress, tokenSource.Token));
    
    OutputStatusMessage(string.Format("Download result file: {0}\n", resultFile));
}

Submit and Download with BulkServiceManager

Submit the download request and then use the BulkDownloadOperation result to track status yourself using GetStatusAsync.

public async Task RunAsync(AuthorizationData authorizationData)
{
    var BulkService = new BulkServiceManager(authorizationData);

    var progress = new Progress<BulkOperationProgressInfo>(x =>
        OutputStatusMessage(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture))));

    var submitDownloadParameters = new SubmitDownloadParameters
    {
        CampaignIds = null,
        DataScope = DataScope.EntityData,
        Entities = BulkDownloadEntity.Keywords,
        FileType = DownloadFileType.Csv,
        LastSyncTimeInUTC = null
    };

    // Submit the download request. You can use the BulkDownloadOperation result to track status yourself using GetStatusAsync,
    // or use TrackAsync to indicate that the application should wait until the download status is completed.

    BulkDownloadOperation bulkDownloadOperation = (await BulkService.SubmitDownloadAsync(submitDownloadParameters));

    BulkOperationStatus<DownloadStatus> downloadStatus;
    var waitTime = new TimeSpan(0, 0, 5);
            
    // This sample polls every 30 seconds up to 5 minutes.
            
    for (int i = 0; i < 10; i++)
    {
        Thread.Sleep(waitTime);

        downloadStatus = await bulkDownloadOperation.GetStatusAsync();

        if (downloadStatus.Status == DownloadStatus.Completed)
        {
            break;
        }
    }

    var resultFile = await bulkDownloadOperation.DownloadResultFileAsync(
        FileDirectory,
        ResultFileName,
        overwrite:false,   // Set this value true if you want to overwrite the same file.
        decompress: true);

    OutputStatusMessage(string.Format("Download result file: {0}\n", resultFile));
}

Download Results with BulkServiceManager

If for any reason you have to resume from a previous application state, you can use an existing download or upload request identifier and use it to download the result file. Use TrackAsync to indicate that the application should wait to ensure that the download status is completed.

public async Task RunAsync(AuthorizationData authorizationData)
{
    BulkService = new BulkServiceManager(authorizationData);

    var progress = new Progress<BulkOperationProgressInfo>(x =>
        OutputStatusMessage(String.Format("{0} % Complete", x.PercentComplete.ToString(CultureInfo.InvariantCulture))));

    // If for any reason you have to resume from a previous application state, you can use an existing download or upload request identifier 
    // and use it to download the result file. 

    BulkDownloadOperation bulkDownloadOperation = new BulkDownloadOperation("<RequestIdGoesHere>", authorizationData);
            
    // Use TrackAsync to indicate that the application should wait to ensure that the download status is completed.
    BulkOperationStatus<DownloadStatus> downloadStatus = await bulkDownloadOperation.TrackAsync(progress, CancellationToken.None);

    OutputStatusMessage(String.Format("Download Status:\nPercentComplete: {0}\nResultFileUrl: {1}\nStatus: {2}",
        downloadStatus.PercentComplete, downloadStatus.ResultFileUrl, downloadStatus.Status));

    var resultFile = await bulkDownloadOperation.DownloadResultFileAsync(
        FileDirectory,
        ResultFileName,
        overwrite: false,   // Set this value true if you want to overwrite the same file.
        decompress: false);

    OutputStatusMessage(string.Format("Download result file: {0}\n", resultFile));

}

Configuring Sandbox

Set the BingAdsEnvironment key to Sandbox within the <appSettings> node of your project root's Web.config (web application) or App.config (desktop application) file.

<add key="BingAdsEnvironment" value ="Sandbox"/>

Community Additions

ADD
Show:
© 2014 Microsoft