Monday, March 7, 2011

Bing API - Using the Bing Translator with C#


This will be the first post of a series about creating a class library for Microsoft Bing APIs in C#. I had ignore Microsoft offering in the past because Google APIs have always done the work for me; however, I recently worked in my first WP7 application and found Bing services to be really mature and capable of delivering results just as good as Google’s. 

Let’s Begin

NOTE:  You need to register and create an AppID at http://www.bing.com/developers.

Create a new project called .NET 4.0 Class Library called DeveloperCaster.Bing; we will wrap all API calls within this class library.




I want to be able to expand this library beyond the translation API so I will leave room to extend it in future posts.
We will begin by adding the following objects:

The Bing Parameter Class - It is a simple value pair class that will be used to represent request parameters to the API.










Source code:
    public class BingParameter
    {
        public string Name
        {
            set;
            get;
        }

        public string Value
        {
            set;
            get;
        }
    }



The IBingRequest Interface – Will be our datatype for request to the Bing service (see BingService class).









Source code:
  public interface IBingRequest
  {
     List<BingParameter> List { get; }
  }


The BingService class – We are going to use this class to execute all our requests to the Bing API.  BingService provide one method to perform a request and I also added an extra method that will take a IBingRequest plus an anonymous method to process a request using the Request(IBingRequest) method to send its return value to the ResponseHandler parameter (not really needed for core functionality). Our class will embed the Bing API URL (“http://api.bing.net/xml.aspx”); however, you may choose not to do so and pass it as a parameter.


















Source Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace DeveloperCaster.Bing
{
    public delegate void ResponseHandler(HttpWebResponse response);

    public class BingService
    {
        private string _api = "http://api.bing.net/xml.aspx";
        private string _appId = "";

        /// <summary>
        /// Default constructor
        /// </summary>
        public BingService()
            : this("")
        { }

        /// <summary>
        /// Contructor with ApiId
        /// </summary>
        /// <param name="appId">AppId</param>
        public BingService(string appId)
        {
            _appId = appId;
        }


        /// <summary>
        /// Request with response handler
        /// </summary>
        /// <param name="r"></param>
        /// <param name="response"></param>
        public void ProcessRequest(IBingRequest r, ResponseHandler response)
        {
            response(Request(r));
        }

        /// <summary>
        /// Request from Api
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public HttpWebResponse Request(IBingRequest r)
        {
            StringBuilder req = new StringBuilder();
            req.Append(this.Api);

            foreach (BingParameter field in r.List)
            {
                req.Append("&" + field.Name + "=" + field.Value);
            }

            HttpWebRequest webRq = (HttpWebRequest)HttpWebRequest.Create(req.ToString());
            HttpWebResponse result = (HttpWebResponse)webRq.GetResponse();
            return result;

        }

        /// <summary>
        /// Get Api
        /// </summary>
        public string Api
        {
            get { return _api + "?AppId=" + _appId; }
        }

        /// <summary>
        /// Set/Get Api
        /// </summary>
        public string AppId
        {
            set { _appId = value; }
            get { return _appId; }
        }

    }

}




Translation Request Object
The translation request will be the first Bing request of our series so let’s being.  The Bing API allows us to request services based on SourceTypes. A SourceType is a source of information available by the API (see full documentation).
To work with the Bing Translation SourceType we will need the following two classes for our object:

The TranslationResponse Class – We will use this object to store our translation API results.











Source Code
using System;

namespace DeveloperCaster.Bing
{
    public class TranslationResponse
    {
        public string SearchedTerms
        {
            set;
            get;
        }

        public string TranslatedTerm
        {
            set;
            get;
        }
    }
}




The TranslationRequest Class – This is or main request object





















Note: Our request object must inherit from the IBingRequest Interface.

Source Code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;

namespace DeveloperCaster.Bing
{

    public class TranslationRequest : IBingRequest
    {

        private List<BingParameter> _items;
        private string _query;
        private string _sourceLanguage;
        private string _targetLanguage;
        private string _version;


        public static TranslationResponse ParseResponse(HttpWebResponse response)
        {
            TranslationResponse result = new TranslationResponse();

            XmlDocument doc = new XmlDocument();
            doc.Load(response.GetResponseStream());
            if (doc.HasChildNodes)
            {
                try
                {
                    if (doc.HasChildNodes)
                    {
                        if (doc["SearchResponse"] != null)
                        {
                            if (doc["SearchResponse"]["Query"]["SearchTerms"] != null)
                            {
                                result.SearchedTerms = doc["SearchResponse"]["Query"]["SearchTerms"].InnerText;
                            }

                            if (doc["SearchResponse"]["tra:Translation"] != null)
                            {
                                result.TranslatedTerm = doc["SearchResponse"]
                                    ["tra:Translation"]
                                    ["tra:Results"]
                                    ["tra:TranslationResult"]["tra:TranslatedTerm"].InnerText;
                            }
                        }

                    }
                }
                catch (NullReferenceException ex)
                {

                }
                catch (XmlException ex)
                {
                }

            }

            return result;
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        public TranslationRequest()
            : this("", "", "", "") { }

        /// <summary>
        /// Second constructor
        /// </summary>
        /// <param name="query">query</param>
        /// <param name="sourceLanguage">source language</param>
        /// <param name="targetLanguage">target language</param>
        public TranslationRequest(string query, string sourceLanguage,
 string targetLanguage)
            : this(query, sourceLanguage, targetLanguage, "2.2") { }

       /// <summary>
       /// Third constructor
       /// </summary>
       /// <param name="query">query</param>
       /// <param name="sourceLanguage">source language</param>
       /// <param name="targetLanguage">target language</param>
       /// <param name="version">api version</param>
public TranslationRequest(string query, string sourceLanguage,
string targetLanguage, string version)
        {
            _items = new List<BingParameter>();
            _items.Add(new BingParameter
            {
                Name = "Sources",
                Value = "Translation"
            });

            if (!Exists("Query"))
            {
                _query = query;
            }
            if (!Exists("Translation.SourceLanguage"))
            {
                _sourceLanguage = sourceLanguage;
            }
            if (!Exists("Translation.TargetLanguage"))
            {
                _targetLanguage = targetLanguage;
            }
            if (!Exists("Version"))
            {
                _version = version;
            }
        }

        private void Add(string name, string val)
        {
            _items.Add(new BingParameter
            {
                Name = name,
                Value = val
            });
        }

        private bool Exists(string name)
        {
            bool result = false;
            foreach (BingParameter f in _items)
            {
                if (f.Name.ToLower() == name.ToLower())
                {
                    result = true;
                    break;
                }
            }

            return result;
        }

        public ResponseHandler Response;

        public string Query
        {
            set
            {
                if (!Exists("Query"))
                {
                    _query = value;
                    Add("Query", value);
                }
            }
            get { return _query; }
        }

        public string SourceLanguage
        {
            set
            {
                if (!Exists("Translation.SourceLanguage"))
                {
                    _sourceLanguage = value;
                    Add("Translation.SourceLanguage", value);
                }
            }

            get { return _sourceLanguage; }
        }

        public string TargetLanguage
        {
            set
            {
                if (!Exists("Translation.TargetLanguage"))
                {
                    _targetLanguage = value;
                    Add("Translation.TargetLanguage", value);
                }
            }

            get { return _targetLanguage; }
        }

        public string Version
        {
            set
            {
                if (!Exists("Version"))
                {
                    _version = value;
                    Add("Version", value);
                }
            }
            get { return _version; }
        }

        /// <summary>
        /// Set/Get Items
        /// </summary>
        public List<BingParameter> List
        {
            get
            {
                return _items;
            }
        }


    }


}




Usage
We will test our library by translating a phrase from English to Spanish. Create a console application, create a reference to our complied dll, and add the following code to test our library:


BingService bing = new BingService("ADD YOUR APPID HERE");

TranslationResponse response =TranslationRequest.ParseResponse(bing.Request(new            TranslationRequest{
                    Query = "Welcome to my blog",
                    SourceLanguage = "en",
                    TargetLanguage = "es"
                  })
);

Console.WriteLine("{0} = {1}", response.SearchedTerms, response.TranslatedTerm);

Console.ReadLine();


Output:
Welcome to my blog = Bienvenido a mi blog





1 comment:

  1. Hey! thanks for great review. It was easy to read, but I'd like to add that if your business needs to be updated try software development service.

    ReplyDelete