Ex Google Employee Reveals Just How Easy It Is To Make Money!
JLForums.com Exclusive Special Offers

Author Topic: TBS Client for .NET (C#, VB, etc)  (Read 759 times)

0 Members and 1 Guest are viewing this topic.

Offline rogerdTopic starter

  • Trade Count: (0)
  • Posting Member
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 9
    • View Profile
    • Awards
TBS Client for .NET (C#, VB, etc)
« on: December 03, 2010, 12:54:51 PM »
I coded up a client that implements all the current API functions available.

This is for Microsoft .NET projects.

PM me if you'd like a copy of the code.
Are your domains out of control? Can you locate any administrative detail for any piece of your IM empire? Probably not.... until now http://domainlab101.com/

Offline pasdoy

  • Trade Count: (0)
  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 3
    • View Profile
    • Email
    • Awards
Re: TBS Client for .NET (C#, VB, etc)
« Reply #1 on: June 07, 2011, 08:31:21 AM »
I bet this was never released right ?

Offline rogerdTopic starter

  • Trade Count: (0)
  • Posting Member
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 9
    • View Profile
    • Awards
Re: TBS Client for .NET (C#, VB, etc)
« Reply #2 on: June 07, 2011, 08:50:24 AM »
Hi Pasdoy,

You're the first person whose contacted me about this so, no, it was never released to this forum. I'd be happy to provide you with a copy of the TBS class, if you're interested.

I've been using it for 6 months now in a private blog network manager and it just hums right along cranking out unique articles for me.

Regards,
Roger
Are your domains out of control? Can you locate any administrative detail for any piece of your IM empire? Probably not.... until now http://domainlab101.com/


Offline pasdoy

  • Trade Count: (0)
  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 3
    • View Profile
    • Email
    • Awards
Re: TBS Client for .NET (C#, VB, etc)
« Reply #3 on: June 07, 2011, 09:02:40 AM »
Hey thank you for your fast reply. I just sent you a PM.

Offline rogerdTopic starter

  • Trade Count: (0)
  • Posting Member
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 9
    • View Profile
    • Awards
Re: TBS Client for .NET (C#, VB, etc)
« Reply #4 on: June 07, 2011, 09:07:11 AM »
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace DCC.Scraper.TBS
{
    /// <summary>
    /// Connect to The Best Spinner API. Allows you to automate some features the client provides.
    /// </summary>
    public class BestSpinnerClient : ScraperBase
    {
        private string _username;
        private string _password;
        private string _sessionId;
        private string _baseUrl;

        public BestSpinnerClient()
        {
            _baseUrl = "http://thebestspinner.com/api.php";
        }
      
      public string Username
      {
         set {
            _username = value;
         }
         
         get {
            return _username;
         }
      }
      
      public string Password
      {
         set {
            _password = value;
         }
         
         get {
            return _password;
         }
      }

        public int ApiQueries
        {
            get
            {
                BestSpinnerRequest req = new BestSpinnerRequest("apiQueries");
                req.Expected.Add("output");
                BestSpinnerResponse resp = SendCommand(req);
                return int.Parse(resp.Values["output"]);
            }
        }
      
      private string SessionId
      {
         set {
            _sessionId = value;
         }
         
         get {
            return _sessionId;
         }
      }

        public void Login(string username, string password)
        {
            Username = username;
            Password = password;

            this.Initialize();
        }

        /// <summary>
        /// Identify Synonyms
        /// </summary>
        /// <param name="text">The text to perform the synonym identification on.</param>
        /// <param name="maxSyns">The maximum number of synonyms to return for a word/phrase.</param>
        /// <returns>A spin-ready string.</returns>
        public string IdentifySynonyms(string text, int maxSyns)
        {
            BestSpinnerRequest req = new BestSpinnerRequest("identifySynonyms");
            req.AddParam("text", text);
            req.AddParam("maxsyns", maxSyns.ToString());
            req.Expected.Add("output");
            BestSpinnerResponse resp = SendCommand(req);
            return resp.Values["output"];
        }

        /// <summary>
        /// Replace Everyone's Favorites
        /// </summary>
        /// <param name="text">The text to perform the synonym identification on.</param>
        /// <param name="maxSyns">The maximum number of synonyms to return for a word/phrase.</param>
        /// <param name="quality">The level of replacements.</param>
        /// <returns>A spin-ready string.</returns>
        public string ReplaceEveryonesFavorites(string text, int maxSyns, SpinQuality quality)
        {
            BestSpinnerRequest req = new BestSpinnerRequest("replaceEveryonesFavorites");
            req.AddParam("text", text);
            req.AddParam("maxsyns", maxSyns.ToString());
            req.AddParam("quality", quality.ToString());
            req.Expected.Add("output");
            BestSpinnerResponse resp = SendCommand(req);
            return resp.Values["output"];
        }

        /// <summary>
        /// Creates a unique article based on spin-formatted text.
        /// </summary>
        /// <param name="text">Spin-formatted text.</param>
        /// <returns>A randomly spun version of text.</returns>
        public string RandomSpin(string text)
        {
            BestSpinnerRequest req = new BestSpinnerRequest("randomSpin");
            req.AddParam("text", text);
            req.Expected.Add("output");
            BestSpinnerResponse resp = SendCommand(req);
            return resp.Values["output"];
        }

        private void Initialize()
        {
            if (string.IsNullOrEmpty(SessionId))
            {
                SessionId = this.Authenticate();
            }
        }

        private string Authenticate()
        {
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
                throw new ArgumentNullException("You must Login() or set the Username and Password before proceeding.");

            BestSpinnerRequest req = new BestSpinnerRequest("authenticate");
            req.AddParam("username", Username);
            req.AddParam("password", Password);
            req.Expected.Add("session");
            BestSpinnerResponse resp = this.SendCommand(req);

            if (resp.Success)
            {
                return resp.Values["session"];
            }
            else
            {
                throw new InvalidOperationException(resp.Values["error"]);
            }
        }

        private BestSpinnerResponse SendCommand(BestSpinnerRequest request)
        {
            if (request == null)
                throw new ArgumentNullException("Request missing.");

            if (request.Expected.Count < 1)
                throw new ArgumentNullException("Request missing expected response fields.");

            if (request.Values.Count < 1)
                throw new ArgumentNullException("Request missing parameters.");

            if (!request.Values["action"].Equals("authenticate") && string.IsNullOrEmpty(SessionId))
                throw new ArgumentNullException("You are not authenticated, please Login().");               
           
            string url = string.Format("&session={0}&format=xml&{1}", SessionId, request.ToString());
           
#if DEBUG
            Console.WriteLine("REQUEST: " + url);           
#endif

            string xml = base.Post(this._baseUrl, url);
            BestSpinnerResponse r = this.ParseResponse(request, xml);

            if (!r.Success)
            {
                throw new InvalidOperationException(string.Format("Action: {0}, Message: {1}", request.Values["action"], r.Values["error"]));
            }

            return r;
        }

        private BestSpinnerResponse ParseResponse(BestSpinnerRequest request, string response)
        {
            if (request == null)
                throw new ArgumentNullException("Request missing.");

            if (string.IsNullOrEmpty(response))
                throw new ArgumentNullException("Missing an XML API response.");

#if DEBUG
            Console.WriteLine("RESPONSE: " + response);
#endif

            BestSpinnerResponse r = new BestSpinnerResponse();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(response);

            string isValid = xmlDoc.DocumentElement.SelectSingleNode("success").InnerText;
            r.Success = bool.Parse(isValid);

            if (r.Success)
            {
                foreach (string node in request.Expected)
                {
                    if (node == null)
                        throw new InvalidOperationException("A null request parameter was found!");

                    string value = xmlDoc.DocumentElement.SelectSingleNode(node).InnerText;
                    r.AddParam(node, value);
                }
            }
            else
            {
                r.AddParam("error", xmlDoc.DocumentElement.SelectSingleNode("error").InnerText);
            }

            return r;
        }       
    }

    /// <summary>
    /// The values for a given API request.
    /// </summary>
    public class BestSpinnerRequest : BestSpinnerPacket
    {
        private List<string> _expected;

        public BestSpinnerRequest(string action)
        {
            AddParam("action", action);
            _expected = new List<string>();
        }
      
        /// <summary>
        /// Stores names of values expected in the response.
        /// </summary>
      public List<string> Expected
      {
         set {
            _expected = value;
         }
         
         get {
            return _expected;
         }
      }       

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair<string, string> item in Values)
            {
                sb.Append(string.Format("{0}={1}&", item.Key, item.Value));
            }

            return sb.ToString();
        }
    }

    /// <summary>
    /// The results of a API request.
    /// </summary>
    public class BestSpinnerResponse : BestSpinnerPacket
    {
        private bool _success;

        public BestSpinnerResponse()
        {
            _success = false;
        }
      
        /// <summary>
        /// Was the API request successful?
        /// </summary>
      public bool Success
      {
         set {
            _success = value;
         }
         
         get {
            return _success;
         }
      }
    }

    public class BestSpinnerPacket
    {
        private Dictionary<string, string> _values;

        public BestSpinnerPacket()
        {
            _values = new Dictionary<string,string>();
        }

        public void AddParam(string name, string value)
        {
            Values.Add(name, value);
        }
      
        /// <summary>
        /// Stores query string parameters on a Request. Stores result values on a Response.
        /// </summary>
      public Dictionary<string, string> Values
      {
         set {
            _values = value;
         }
         
         get {
            return _values;
         }
      }
    }

    public enum SpinQuality
    {
        Good = 1,
        Better = 2,
        Best = 3
    }
}

--------- Here are some Unit Tests to see how it works ----------

using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using DCC.Scraper.TBS;

namespace UnitTests
{
    [TestFixture]
    public class BestSpinnerTests
    {
        private BestSpinnerClient CreateClient()
        {
            BestSpinnerClient tbs = new BestSpinnerClient();
            tbs.Login("your-tbs-email", "your-tbs-api-key");
            return tbs;
        }

        [Test]
        public void Can_Authenticate_Client()
        {
            BestSpinnerClient tbs = this.CreateClient();
            Console.WriteLine("Queries: " + tbs.ApiQueries);
            Assert.IsTrue(tbs.ApiQueries >= 0);
        }

        [Test]
        [ExpectedException(typeof(ArgumentNullException))]
        public void Stops_If_Not_Logged_In()
        {
            BestSpinnerClient tbs = new BestSpinnerClient();
            int queries = tbs.ApiQueries;
        }

        [Test]
        public void Can_Identify_Synonyms()
        {
            BestSpinnerClient tbs = this.CreateClient();
            string spinText = tbs.IdentifySynonyms("Losing weight can be a difficult thing to do.", 3);
            //Console.WriteLine(spinText);
            Assert.IsTrue(spinText.IndexOf("{") > -1);
            Assert.IsTrue(spinText.IndexOf("}") > -1);
            Assert.IsTrue(spinText.IndexOf("|") > -1);
        }

        [Test]
        public void Can_Replace_Everyones_Favories()
        {
            BestSpinnerClient tbs = this.CreateClient();
            string spinText = tbs.ReplaceEveryonesFavorites("Losing weight can be a difficult thing to do.", 3, SpinQuality.Good);
            //Console.WriteLine(spinText);
            Assert.IsTrue(spinText.IndexOf("{") > -1);
            Assert.IsTrue(spinText.IndexOf("}") > -1);
            Assert.IsTrue(spinText.IndexOf("|") > -1);
        }

        [Test]
        public void Can_Spin_Text()
        {
            BestSpinnerClient tbs = this.CreateClient();
            string spun = tbs.RandomSpin("{Losing|Dropping|Shedding} {weight|fat|bodyweight|excess weight} can be a {difficult|challenging|tough|hard} {thing|factor|issue|point} to do.");
            //Console.WriteLine(spun);
            Assert.IsTrue(spun.IndexOf("{") == -1);
            Assert.IsTrue(spun.IndexOf("}") == -1);
            Assert.IsTrue(spun.IndexOf("|") == -1);
        }
    }
}

Are your domains out of control? Can you locate any administrative detail for any piece of your IM empire? Probably not.... until now http://domainlab101.com/

Offline pasdoy

  • Trade Count: (0)
  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 3
    • View Profile
    • Email
    • Awards
Re: TBS Client for .NET (C#, VB, etc)
« Reply #5 on: June 07, 2011, 09:32:13 AM »
Thank you for posting the code here. I hope it will help others.
I am currently working on 2.0, I will wait to be home on 4.0 to test it.
Thank you.

Offline akrosoft

  • Trade Count: (0)
  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 1
    • View Profile
    • Awards
Re: TBS Client for .NET (C#, VB, etc)
« Reply #6 on: October 04, 2011, 06:53:11 AM »
Hi,
can I get a copy of C# api for tbs.
I tried to use your code on forum but ScraperBase is missing.

Thanks!

Offline rogerdTopic starter

  • Trade Count: (0)
  • Posting Member
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 9
    • View Profile
    • Awards
Re: TBS Client for .NET (C#, VB, etc)
« Reply #7 on: October 04, 2011, 08:37:11 AM »
Yes, that would be helpful! :p

Code: [Select]
    public abstract class ScraperBase
    {
        private string _userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7";
        private CookieContainer _cookieJar;
        private bool _debug;

        public ScraperBase()
        {
            this._cookieJar = new CookieContainer();
        }

internal string UserAgent
{
set {
_userAgent = value;
}

get {
return _userAgent;
}
}

internal CookieContainer CookieJar
{
set {
_cookieJar = value;
}

get {
return _cookieJar;
}
}

internal bool Debug
{
set {
_debug = value;
}

get {
return _debug;
}
}

        internal string Post(string url, string postData)
        {
            byte[] postBytes = Encoding.Default.GetBytes(postData);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.UserAgent = this.UserAgent;
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = postBytes.Length;
            req.CookieContainer = this.CookieJar;

            Stream dataStream = req.GetRequestStream();
            dataStream.Write(postBytes, 0, postBytes.Length);
            dataStream.Close();

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            dataStream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(dataStream);

            string response = sr.ReadToEnd();

            sr.Close();
            dataStream.Close();
            resp.Close();

            //if (this.Debug)
            //{
            //    Console.WriteLine(string.Format("Plugin: {2}\nParameters: {3}\nPOST Response [{1}]:\n{0}", response, queryString, this.ProgramName, postData));
            //}

            return response;
        }

        internal string Get(string url)
        {
            if (this.Debug)
            {
                Console.WriteLine(string.Format("Making GET: {0}", url));
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.UserAgent = this.UserAgent;
            req.CookieContainer = this.CookieJar;
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Stream dataStream = resp.GetResponseStream();
            StreamReader sr = new StreamReader(dataStream);

            string response = sr.ReadToEnd();

            sr.Close();
            dataStream.Close();

            if (this.Debug)
            {
                Console.WriteLine(string.Format("GET Response:\n{0}", response));
            }

            return response;
        }

        internal Cookie FindCookie(string url, string cookieToFind)
        {
            CookieCollection cookies = this.FindCookies(url);
            Cookie r = null;

            for (int i = 0; i < cookies.Count; i++)
            {
                Cookie c = cookies[i];

                if (c.Name.Equals(cookieToFind))
                {
                    r = c;
                }
            }

            return r;
        }

        internal CookieCollection FindCookies(string url)
        {
            if (url == string.Empty)
                throw new ArgumentNullException("url");

            CookieCollection cookies = this.CookieJar.GetCookies(new Uri(url));
            return cookies;
        }

        internal void CookieDump(string url)
        {
            CookieCollection cookies = this.FindCookies(url);

            for (int i = 0; i < cookies.Count; i++)
            {
                Cookie c = cookies[i];
                Console.WriteLine(c.Name + " => " + c.Value);
            }
        }

        internal string UrlEncode(string raw)
        {
            return HttpUtility.UrlEncode(raw);
        }

        internal string HtmlDecode(string encoded)
        {
            return HttpUtility.HtmlDecode(encoded);
        }

        internal string RegexMatch(string input, string pattern)
        {
            Match m = Regex.Match(input, pattern, RegexOptions.Singleline | RegexOptions.Multiline);
            return m.Success ? m.Groups[1].Value : null;
        }

        internal MatchCollection RegexMatches(string input, string pattern)
        {
            return Regex.Matches(input, pattern, RegexOptions.Multiline | RegexOptions.Singleline);
        }
    }
Are your domains out of control? Can you locate any administrative detail for any piece of your IM empire? Probably not.... until now http://domainlab101.com/