Compartilhar via


Using Bing API’s to display Ads

In this post I will give you a quick introduction on how to use the Bing API’s SOAP protocol to generate Ads. Bing API’s are a very complex piece of web services with lots of options for very powerful and configurable serving of Ads.

1. Using Visual Studio 2010, create a new Console Application and name it “AdsSample

clip_image002

2. Adding a web reference

             clip_image003

  • You should now see a web reference as below. If this step was not successfully created, it could be that your appid has not been approved or you are providing an incorrect appid. Please check with the appropriate folks.

             clip_image004

  • The following References should be available in your solution. If not add them to your project

            clip_image005

3. Place the following content in Program.cs

 using System;
using System.Xml;
using System.ServiceModel;
using System.Web;
using AdsSample.net.bing.api;

namespace AdsSample
{
    static class Program
    {
        // Replace the following string with the AppId you received from the
        // Bing Developer Center.
        const string AppId = "AppId";

        // Replace the values of AdUnitId and PropertyId with the values you
        // received from AdCenter.
        const uint AdUnitId = AdUnitId;
        const uint PropertyId = PropertyId;

        static void Main(string[] args)
        {
            // BingService implements IDisposable.
            using (BingPortTypeClient service = new BingPortTypeClient())
            {
                try
                {
                    SearchRequest request = BuildRequest();

                    // Send the request; display the response.
                    SearchResponse response = service.Search(request);
                    DisplayResponse(response);
                    Console.WriteLine("Press any key to exit.....");
                    Console.ReadKey();
                }
                catch (System.Net.WebException ex)
                {
                    // An exception occurred while accessing the network.
                    Console.WriteLine(ex.Message);
                }
            }
        }

        static SearchRequest BuildRequest()
        {
            SearchRequest request = new SearchRequest();

            // Common request fields (required)
            request.AppId = AppId;
            request.Query = "computers";
            request.Sources = new SourceType[] { SourceType.Ad };

            // Common request fields (optional)
            request.Version = "2.0";
            request.Market = "en-us";
            request.Options = new SearchOption[]
            {
                SearchOption.EnableHighlighting 
            };


            // Ad-specific request fields (required)
            request.Ad = new AdRequest();
            request.Ad.AdUnitId = AdUnitId;
            request.Ad.PropertyId = PropertyId;
            request.Ad.PageNumber = 0;

            // Ad-specific request fields (optional)
            request.Ad.MlAdCount = 5;
            request.Ad.MlAdCountSpecified = true;
            request.Ad.SbAdCount = 5;
            request.Ad.SbAdCountSpecified = true;
            request.Ad.ChannelId = "0";

            return request;
        }

        static void DisplayResponse(SearchResponse response)
        {
            // Display the results header.
            Console.WriteLine("Bing API Version " + response.Version);
            Console.WriteLine(
                "Ad "
                + response.Ad.AdApiVersion
                + " results for "
                + response.Query.SearchTerms);
            Console.WriteLine();

            // Display the Ad results.
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            foreach (AdResult result in response.Ad.Results)
            {
                builder.Length = 0;
                builder.AppendLine(result.Title);
                builder.AppendLine(result.DisplayUrl);
                builder.AppendLine(result.AdLinkUrl);
                builder.AppendLine(result.Description);
               builder.AppendLine("Position: " + result.Position);

                DisplayTextWithHighlighting(builder.ToString());
                Console.WriteLine();
            }
        }

        static void DisplayTextWithHighlighting(string text)
        {
            // Write text to the standard output stream, changing the console
            // foreground color as highlighting characters are encountered.
            foreach (char c in text.ToCharArray())
            {
                if (c == '\uE000')
                {
                    // If the current character is the begin highlighting
                    // character (U+E000), change the console foreground color
                    // to green.
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                else if (c == '\uE001')
                {
                    // If the current character is the end highlighting
                    // character (U+E001), revert the console foreground color
                    // to gray.
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else
                {
                    Console.Write(c);
                }
            }
        }

        static void DisplayErrors(XmlNode errorDetails)
        {
            // Add the default namespace to the namespace manager.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(
                errorDetails.OwnerDocument.NameTable);
            nsmgr.AddNamespace(
                "api",
                "https://schemas.microsoft.com/LiveSearch/2008/03/Search");

            XmlNodeList errors = errorDetails.SelectNodes(
                "./api:Errors/api:Error",
                nsmgr);

            if (errors != null)
            {
                // Iterate over the list of errors and display error details.
                Console.WriteLine("Errors:");
                Console.WriteLine();
                foreach (XmlNode error in errors)
                {
                    foreach (XmlNode detail in error.ChildNodes)
                    {
                        Console.WriteLine(detail.Name + ": " + detail.InnerText);
                    }

                    Console.WriteLine();
                }
            }
        }
    }
}

4. Build the project (Ctrl+Shift+B)

5. Run F5 to see the ads on the console application

That’s it. You should now see the ad contents being written out to the console. In future articles in this series, I will explain more on different ad types and monetization!

Comments

  • Anonymous
    December 25, 2010
  1. shall user can share results of Bing Api in facebook wall.
  2. is it compulsory to add Bing logo in bing api when showing the results of  bing