martes, 22 de marzo de 2011

Versión C# del Wrapper para consumir la API del Wolfram Alpha

Wolfram Alfa, al igual que otros motores de búsqueda o computo del conocimiento expone su API para utilizar la bastitud de herramientas de calculo computacional con las que cuenta, utilizando una API sencilla escrita en VB.NET, pero para aquellos que no nos gusta (VB) o que preferimos utilizar C# por estándares esta es una opción para integrar la funcionalidad de calculo del Wolfram en nuestras apps.




Ejemplo de utilización de la API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using F.IA.WolframAlpha;


namespace WATest
{
    public class WolframAlphaWrapperExample
    {


        F.IA.WolframAlpha.WolframAlphaEngine Engine = new F.IA.WolframAlpha.WolframAlphaEngine();

        public void Output(string Data, int Indenting, System.ConsoleColor Color)
        {
            for (int i=0;i<Indenting * 4;i++){
                Data = " " + Data;
            }
           

            Console.ForegroundColor = Color;
            Console.WriteLine(Data);
            Console.ForegroundColor = ConsoleColor.White;

            System.IO.StreamWriter Writer = new System.IO.StreamWriter(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Wolfram Alpha wrapper log.log", true);
            Writer.WriteLine(Data);
            Writer.Close();
            Writer.Dispose();

        }


        public void Process(string qry, System.Windows.Forms.Control container)
        {
            //Try to delete the log file if it already exists.
            try
            {
                System.IO.File.Delete(System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Wolfram Alpha wrapper log.log");
            }
            catch
            {
            }

            //Define what our application ID is.
            string WolframAlphaApplicationID = "beta824g1";

            //Define what we want to search for.
            string WolframAlphaSearchTerms =qry;

            //Print out what we're about to do in the console.
            Output("Getting response for the search terms \"" + WolframAlphaSearchTerms + "\" and the application ID string \"" + WolframAlphaApplicationID + "\" ...", 0, ConsoleColor.White);

            //Use the engine to get a response, from the application ID specified, and the search terms.
            F.IA.WolframAlpha.WolframAlphaQuery query = new F.IA.WolframAlpha.WolframAlphaQuery();
            query.APIKey = WolframAlphaApplicationID;
            query.Query = WolframAlphaSearchTerms;

            Engine.LoadResponse(query);

            //Print out a message saying that the last task was successful.
            Output("Response injected.", 0, ConsoleColor.White);

            //Make 2 empty spaces in the console.
            Output("", 0, ConsoleColor.White);

            Output("Response details", 1, ConsoleColor.Blue);

            //Print out how many different pods that were found.
            Output("Pods found: " + Engine.QueryResult.NumberOfPods, 1, ConsoleColor.White);
            Output("Query pasing time: " + Engine.QueryResult.ParseTiming + " seconds", 1, ConsoleColor.White);
            Output("Query execution time: " + Engine.QueryResult.Timing + " seconds", 1, ConsoleColor.White);

            int PodNumber = 1;

          
           
            foreach (WolframAlphaPod Item in Engine.QueryResult.Pods)
            {
                //Make an empty space in the console.
                Output("", 0, ConsoleColor.White);

                Output("Pod " + PodNumber, 2, ConsoleColor.Red);

                Output("Sub pods found: " + Item.NumberOfSubPods, 2, ConsoleColor.White);
                Output("Title: \"" + Item.Title + "\"", 2, ConsoleColor.White);
                Output("Position: " + Item.Position, 2, ConsoleColor.White);

                int SubPodNumber = 1;

               
                foreach (WolframAlphaSubPod SubItem in Item.SubPods)
                {
                    Output("", 0, ConsoleColor.White);

                    Output("Sub pod " + SubPodNumber, 3, ConsoleColor.Magenta);
                    Output("Title: \"" + SubItem.Title + "\"", 3, ConsoleColor.White);
                    Output("Pod text: \"" + SubItem.PodText + "\"", 3, ConsoleColor.White);
                    Output("Pod image title: \"" + SubItem.PodImage.Title + "\"", 3, ConsoleColor.White);
                    Output("Pod image width: " + SubItem.PodImage.Width, 3, ConsoleColor.White);
                    Output("Pod image height: " + SubItem.PodImage.Height, 3, ConsoleColor.White);
                    Output("Pod image location: \"" + SubItem.PodImage.Location.ToString() + "\"", 3, ConsoleColor.White);
                    Output("Pod image description text: \"" + SubItem.PodImage.HoverText + "\"", 3, ConsoleColor.White);

                    if ((container as System.Windows.Forms.TableLayoutPanel).RowCount < SubPodNumber)
                        (container as System.Windows.Forms.TableLayoutPanel).RowCount = SubPodNumber;

                    (container as System.Windows.Forms.TableLayoutPanel ).Controls.Add (new System.Windows.Forms.PictureBox (){ ImageLocation = SubItem.PodImage.Location.AbsoluteUri ,
                     SizeMode= System.Windows.Forms.PictureBoxSizeMode.AutoSize
                    },0, SubPodNumber-1);
                  
                    SubPodNumber += 1;

                   

                }

                PodNumber += 1;


            }

         

            //Make an empty space in the console.
            Output("", 0, ConsoleColor.White);

            //Make the application stay open until there is user interaction.
            Output("All content has been saved to " + System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Wolfram Alpha wrapper log.log. Press a key to close the example.", 0, ConsoleColor.Green);
            Console.ReadLine();

        }
    }
}





Clases para encapsular la API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace F.IA.WolframAlpha
{

    public class WolframAlphaValidationResult
    {

        private string WA_ParseData;
        private List<WolframAlphaAssumption> WA_Assumptions;
        private bool WA_Success;
        private bool WA_Error;

        private double WA_Timing;
        public bool Success
        {
            get { return WA_Success; }
            set { WA_Success = value; }
        }

        public string ParseData
        {
            get { return WA_ParseData; }
            set { WA_ParseData = value; }
        }

        public List<WolframAlphaAssumption> Assumptions
        {
            get { return WA_Assumptions; }
            set { WA_Assumptions = value; }
        }

        public bool ErrorOccured
        {
            get { return WA_Error; }
            set { WA_Error = value; }
        }

        public double Timing
        {
            get { return WA_Timing; }
            set { WA_Timing = value; }
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace F.IA.WolframAlpha
{

    public class WolframAlphaSubPod
    {


        public string Title
        {
            get;
            set;
        }

        public string PodText
        {
            get;
            set;
        }

        public WolframAlphaImage PodImage
        {
            get;
            set;
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace F.IA.WolframAlpha
{

    public class WolframAlphaQueryResult
    {

        private List<WolframAlphaPod> WA_Pods;
      
        public List<WolframAlphaPod> Pods
        {
            get { return WA_Pods; }
            set { WA_Pods = value; }
        }

        public bool Success
        {
            get;
            set;
        }

        public bool ErrorOccured
        {
            get;
            set;
        }

        public int NumberOfPods
        {
            get;
            set;
        }

        public string DataTypes
        {
            get;
            set;
        }

        public string TimedOut
        {
            get;
            set;
        }

        public double Timing
        {
            get;
            set;
        }

        public double ParseTiming
        {
            get;
            set;
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;



namespace F.IA.WolframAlpha
{

    public class WolframAlphaQuery
    {

        private const string MainRoot = "http://api.wolframalpha.com/v1/query.jsp";


        private string WA_APIKey;
        public string APIKey
        {
            get { return WA_APIKey; }
            set { WA_APIKey = value; }
        }

        private string WA_Format;
        private string WA_Substitution;
        private string WA_Assumption;
        private string WA_Query;
        private string WA_PodTitle;
        private int WA_TimeLimit;
        private bool WA_AllowCached;
        private bool WA_Asynchronous;

        private bool WA_MoreOutput;
        public bool MoreOutput
        {
            get { return WA_MoreOutput; }
            set { WA_MoreOutput = value; }
        }

        public string Format
        {
            get { return WA_Format; }
            set { WA_Format = value; }
        }

        public bool Asynchronous
        {
            get { return WA_Asynchronous; }
            set { WA_Asynchronous = value; }
        }

        public bool AllowCaching
        {
            get { return WA_AllowCached; }
            set { WA_AllowCached = false; }
        }

        public string Query
        {
            get { return WA_Query; }
            set { WA_Query = value; }
        }

        public int TimeLimit
        {
            get { return WA_TimeLimit; }
            set { WA_TimeLimit = value; }
        }

        public void AddPodTitle(string PodTitle, bool CheckForDuplicates = false)
        {
            if (CheckForDuplicates == true && WA_PodTitle.Contains("&PodTitle=" + HttpUtility.UrlEncode(PodTitle)))
            {
                return;
            }
            WA_PodTitle += "&podtitle=" + HttpUtility.UrlEncode(PodTitle);
        }

        public void AddSubstitution(string Substitution, bool CheckForDuplicates = false)
        {
            if (CheckForDuplicates == true && WA_Substitution.Contains("&substitution=" + HttpUtility.UrlEncode(Substitution)))
            {
                return;
            }
            WA_Substitution += "&substitution=" + HttpUtility.UrlEncode(Substitution);
        }

        public void AddAssumption(string Assumption, bool CheckForDuplicates = false)
        {
            if (CheckForDuplicates == true && WA_Assumption.Contains("&substitution=" + HttpUtility.UrlEncode(Assumption)))
            {
                return;
            }
            
            WA_Assumption += "&assumption=" + HttpUtility.UrlEncode(Assumption);
        }

        public void AddAssumption(WolframAlphaAssumption Assumption, bool CheckForDuplicates = false)
        {
            if (CheckForDuplicates == true && WA_Assumption.Contains("&substitution=" + HttpUtility.UrlEncode(Assumption.Word)))
            {
                return;
            }
            WA_Assumption += "&assumption=" + HttpUtility.UrlEncode(Assumption.Word);
        }

        public string[] Substitutions
        {
            get { return WA_Substitution.Split(new string[] { "&substitution=" }, StringSplitOptions.RemoveEmptyEntries); }
        }

        public string[] Assumptions
        {
            get { return WA_Assumption.Split(new string[] { "&assumption=" }, StringSplitOptions.RemoveEmptyEntries); }
        }

        public string[] PodTitles
        {
            get { return WA_PodTitle.Split(new string[] { "&assumption=" }, StringSplitOptions.RemoveEmptyEntries); }
        }

        public string FullQueryString
        {
            get { return "?appid=" + WA_APIKey + "&moreoutput=" + MoreOutput + "&timelimit=" + TimeLimit + "&format=" + WA_Format + "&input=" + WA_Query + WA_Assumption + WA_Substitution; }
        }

        public class WolframAlphaQueryFormat
        {
            public static string Image = "image";
            public static string HTML = "html";
            public static string PDF = "pdf";
            public static string PlainText = "plaintext";
            public static string MathematicaInput = "minput";
            public static string MathematicaOutput = "moutput";
            public static string MathematicaMathMarkupLanguage = "mathml";
            public static string MathematicaExpressionMarkupLanguage = "expressionml";
            public static string ExtensibleMarkupLanguage = "xml";
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace F.IA.WolframAlpha
{

    public class WolframAlphaPod
    {

        private List<WolframAlphaSubPod> WA_SubPods;
      
        public List<WolframAlphaSubPod> SubPods
        {
            get { return WA_SubPods; }
            set { WA_SubPods = value; }
        }

        public string Title
        {
            get;
            set;
        }

        public string Scanner
        {
            get;
            set;
        }

        public int Position
        {
            get;
            set;
        }

        public bool ErrorOccured
        {
            get;
            set;
        }

        public int NumberOfSubPods
        {
            get;
            set;
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace F.IA.WolframAlpha
{
  
    public class WolframAlphaImage
    {

        public Uri Location
        {
            get;
            set;
        }

        public int Width
        {
            get;
            set;
        }

        public int Height
        {
            get;
            set;
        }

        public string Title
        {
            get;
            set;
        }

        public string HoverText
        {
            get;
            set;
        }

    }
   
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace F.IA.WolframAlpha
{

    public class WolframAlphaEngine
    {


        private string WA_APIKey;
        private WolframAlphaQueryResult WA_QueryResult;

        private WolframAlphaValidationResult WA_ValidationResult;
        public WolframAlphaEngine(string APIKey)
        {
            WA_APIKey = APIKey;
        }

        public WolframAlphaEngine()
        {
            // TODO: Complete member initialization
        }

        public string APIKey
        {
            get { return WA_APIKey; }
            set { WA_APIKey = value; }
        }

        public WolframAlphaQueryResult QueryResult
        {
            get { return WA_QueryResult; }
        }

        public WolframAlphaValidationResult ValidationResult
        {
            get { return WA_ValidationResult; }
        }

        #region "Overloads of ValidateQuery"

        public WolframAlphaValidationResult ValidateQuery(WolframAlphaQuery Query)
        {

            if (string.IsNullOrEmpty(Query.APIKey))
            {
                if (string.IsNullOrEmpty(this.APIKey))
                {
                    throw new Exception("To use the Wolfram Alpha API, you must specify an API key either through the parsed WolframAlphaQuery, or on the WolframAlphaEngine itself.");
                }
                Query.APIKey = this.APIKey;
            }

            if (Query.Asynchronous == true && Query.Format == WolframAlphaQuery.WolframAlphaQueryFormat.HTML)
            {
                throw new Exception("Wolfram Alpha does not allow asynchronous operations while the format for the query is not set to \"HTML\".");
            }

            System.Net.HttpWebRequest WebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://preview.wolframalpha.com/api/v1/validatequery.jsp" + Query.FullQueryString);
            WebRequest.KeepAlive = true;
            string Response = new System.IO.StreamReader(WebRequest.GetResponse().GetResponseStream()).ReadToEnd();

            return ValidateQuery(Response);

        }

        public WolframAlphaValidationResult ValidateQuery(string Response)
        {

            System.Xml.XmlDocument Document = new System.Xml.XmlDocument();
            WolframAlphaValidationResult Result = null;
            try
            {
                Document.LoadXml(Response);
                Result = ValidateQuery(Document);
            }
            catch
            {
            }
            Document = null;

            return Result;

        }

        public WolframAlphaValidationResult ValidateQuery(System.Xml.XmlDocument Response)
        {

            System.Threading.Thread.Sleep(1);

            System.Xml.XmlNode MainNode = Response.SelectNodes("/validatequeryresult")[0];

            WA_ValidationResult = new WolframAlphaValidationResult();
            WA_ValidationResult.Success = Convert.ToBoolean ( MainNode.Attributes["success"].Value);
            WA_ValidationResult.ErrorOccured = Convert.ToBoolean (MainNode.Attributes["error"].Value);
            WA_ValidationResult.Timing = Convert.ToDouble (MainNode.Attributes["timing"].Value);
            WA_ValidationResult.ParseData = MainNode.SelectNodes("parsedata")[0].InnerText;
            WA_ValidationResult.Assumptions = new List<WolframAlphaAssumption>();


            foreach (System.Xml.XmlNode Node in MainNode.SelectNodes("assumptions"))
            {
                System.Threading.Thread.Sleep(1);

                WolframAlphaAssumption Assumption = new WolframAlphaAssumption();

                Assumption.Word = Node.SelectNodes("word")[0].InnerText;

                System.Xml.XmlNode SubNode = Node.SelectNodes("categories")[0];


                foreach (System.Xml.XmlNode ContentNode in SubNode.SelectNodes("category"))
                {
                    System.Threading.Thread.Sleep(1);

                    Assumption.Categories.Add(ContentNode.InnerText);

                }

                WA_ValidationResult.Assumptions.Add(Assumption);

            }

            return WA_ValidationResult;

        }

        #endregion

        #region "Overloads of LoadResponse"

        public WolframAlphaQueryResult LoadResponse(WolframAlphaQuery Query)
        {

            if (string.IsNullOrEmpty(Query.APIKey))
            {
                if (string.IsNullOrEmpty(this.APIKey))
                {
                    throw new Exception("To use the Wolfram Alpha API, you must specify an API key either through the parsed WolframAlphaQuery, or on the WolframAlphaEngine itself.");
                }
                Query.APIKey = this.APIKey;
            }

            if (Query.Asynchronous == true && Query.Format == WolframAlphaQuery.WolframAlphaQueryFormat.HTML)
            {
                throw new Exception("Wolfram Alpha does not allow asynchronous operations while the format for the query is not set to \"HTML\".");
            }

            System.Net.HttpWebRequest WebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://preview.wolframalpha.com/api/v1/query.jsp" + Query.FullQueryString);
            WebRequest.KeepAlive = true;
            string Response = new System.IO.StreamReader(WebRequest.GetResponse().GetResponseStream()).ReadToEnd();

            return LoadResponse(Response);

        }
        public WolframAlphaQueryResult LoadResponse(string Response)
        {

            System.Xml.XmlDocument Document = new System.Xml.XmlDocument();
            WolframAlphaQueryResult Result = null;
            try
            {
                Document.LoadXml(Response);
                Result = LoadResponse(Document);
            }
            catch
            {
            }
            Document = null;

            return Result;

        }
        public WolframAlphaQueryResult LoadResponse(System.Xml.XmlDocument Response)
        {

            System.Threading.Thread.Sleep(1);

            System.Xml.XmlNode MainNode = Response.SelectNodes("/queryresult")[0];
            WA_QueryResult = new WolframAlphaQueryResult();
            WA_QueryResult.Success =Convert.ToBoolean  ( MainNode.Attributes["success"].Value);
            WA_QueryResult.ErrorOccured = Convert.ToBoolean ( MainNode.Attributes["error"].Value);
            WA_QueryResult.NumberOfPods = Convert.ToInt32 ( MainNode.Attributes["numpods"].Value);
            WA_QueryResult.Timing = Convert.ToDouble  (MainNode.Attributes["timing"].Value);
            WA_QueryResult.TimedOut = MainNode.Attributes["timedout"].Value;
            WA_QueryResult.DataTypes = MainNode.Attributes["datatypes"].Value;
            WA_QueryResult.Pods = new List<WolframAlphaPod>();


            foreach (System.Xml.XmlNode Node in MainNode.SelectNodes("pod"))
            {
                System.Threading.Thread.Sleep(1);

                WolframAlphaPod Pod = new WolframAlphaPod();

                Pod.Title = Node.Attributes["title"].Value;
                Pod.Scanner = Node.Attributes["scanner"].Value;
                Pod.Position = Convert.ToInt32 (Node.Attributes["position"].Value);
                Pod.ErrorOccured = Convert.ToBoolean (Node.Attributes["error"].Value);
                Pod.NumberOfSubPods = Convert.ToInt32 (Node.Attributes["numsubpods"].Value);
                Pod.SubPods = new List<WolframAlphaSubPod>();


                foreach (System.Xml.XmlNode SubNode in Node.SelectNodes("subpod"))
                {
                    System.Threading.Thread.Sleep(1);

                    WolframAlphaSubPod SubPod = new WolframAlphaSubPod();
                    SubPod.Title = SubNode.Attributes["title"].Value;


                    foreach (System.Xml.XmlNode ContentNode in SubNode.SelectNodes("plaintext"))
                    {
                        System.Threading.Thread.Sleep(1);

                        SubPod.PodText = ContentNode.InnerText;

                    }


                    foreach (System.Xml.XmlNode ContentNode in SubNode.SelectNodes("img"))
                    {
                        System.Threading.Thread.Sleep(1);

                        WolframAlphaImage Image = new WolframAlphaImage();
                        Image.Location = new Uri(ContentNode.Attributes["src"].Value);
                        Image.HoverText = ContentNode.Attributes["alt"].Value;
                        Image.Title = ContentNode.Attributes["title"].Value;
                        Image.Width = Convert.ToInt32 ( ContentNode.Attributes["width"].Value);
                        Image.Height = Convert.ToInt32 (ContentNode.Attributes["height"].Value);
                        SubPod.PodImage = Image;

                    }

                    Pod.SubPods.Add(SubPod);

                }

                WA_QueryResult.Pods.Add(Pod);

            }

            return WA_QueryResult;

        }

        #endregion





    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace F.IA.WolframAlpha
{

    public class WolframAlphaAssumption
    {

        private string WA_Word;

        private List<string> WA_Categories = new List<string>();
        public string Word
        {
            get { return WA_Word; }
            set { WA_Word = value; }
        }

        public List<string> Categories
        {
            get { return WA_Categories; }
            set { WA_Categories = value; }
        }

    }
}


Transacciones Fiori

  /UI2/CACHE Register service for UI2 cache use /UI2/CACHE_DEL Delete cache entries /UI2/CHIP Chip Registration /UI2/CUST Customizing of UI ...