<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Kash Farooq&#039;s software development blog</title>
	<atom:link href="http://kashfarooq.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://kashfarooq.wordpress.com</link>
	<description>.NET Developer</description>
	<lastBuildDate>Thu, 26 Jan 2012 17:38:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='kashfarooq.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Kash Farooq&#039;s software development blog</title>
		<link>http://kashfarooq.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://kashfarooq.wordpress.com/osd.xml" title="Kash Farooq&#039;s software development blog" />
	<atom:link rel='hub' href='http://kashfarooq.wordpress.com/?pushpress=hub'/>
		<item>
		<title>BDD with SpecFlow and Coypu (Part 2)</title>
		<link>http://kashfarooq.wordpress.com/2011/08/23/bdd-with-specflow-and-coypu-part-2/</link>
		<comments>http://kashfarooq.wordpress.com/2011/08/23/bdd-with-specflow-and-coypu-part-2/#comments</comments>
		<pubDate>Tue, 23 Aug 2011 20:48:42 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[Behaviour Driven Development]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Coypu]]></category>
		<category><![CDATA[SpecFlow]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=733</guid>
		<description><![CDATA[In my last post I introduced BDD with SpecFlow. I created a  feature file and got to a point where I now needed to hook up my BDD tests with browser integration. To do this, I&#8217;m going to use Coypu and the Selenium headless browser. See my previous post for download links. First, let&#8217;s configure [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=733&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my last post I introduced <a href="http://kashfarooq.wordpress.com/2011/08/19/bdd-with-specflow-and-coypu-part-1/">BDD with SpecFlow</a>. I created a  feature file and got to a point where I now needed to hook up my BDD tests with browser integration. To do this, I&#8217;m going to use Coypu and the Selenium headless browser. See my <a href="http://kashfarooq.wordpress.com/2011/08/19/bdd-with-specflow-and-coypu-part-1/">previous post for download links</a>.</p>
<p>First, let&#8217;s configure Coypu to use the Selenium headless browser:</p>
<p><pre class="brush: csharp;">
[Binding]
public class CoypuInitializer {
    [BeforeTestRun]
    public static void BeforeTestRun()
    {
        //I'm using the Dev Studio cassini server;
        Configuration.AppHost = &quot;localhost&quot;;
        Configuration.Port = 64567;

        ConfigureForHeadlessBrowser();
    }

    private static void ConfigureForHeadlessBrowser()
    {
        Configuration.Driver = typeof(SeleniumHtmlUnitWebDriver);
    }

    [AfterScenario]
    public static void AfterScenario()
    {
        Coypu.Browser.EndSession();
    }
}
</pre><br />
<pre class="brush: csharp;">
public class SeleniumHtmlUnitWebDriver : SeleniumWebDriver {
    public SeleniumHtmlUnitWebDriver() : base(new RemoteWebDriver(DesiredCapabilities.HtmlUnit())) {}
}
</pre></p>
<p>You will also need to add DLL references to Coypu.dll and WebDriver.dll (which is in the Coypu zip).</p>
<p>You can use this class to make other global configuration settings such as the Timeout, or the time Coypu waits between retries when looking for a HTML element. Full details can be found at the <a href="https://github.com/featurist/Coypu">GitHub Coypu website</a>, or the README.md file that comes with the Coypu binaries.</p>
<p>Now we are ready to implement the first feature step. As a reminder, the feature file is:</p>
<p><pre class="brush: plain;">
Scenario: Display Pi using Taylor series and Bucknall's BigNumber to many decimal places
	Given I visit the Pi.NET website
	And I have selected the 'Bucknall Big Number' algorithm
	And I have entered 500 decimal places
	When I press Go
	Then Pi should be displayed to the correct number of decimal places
	And Calculation statistics should be displayed
</pre></p>
<p>Let&#8217;s implement the &#8220;Given I visit the Pi.NET website&#8221; step:</p>
<p><pre class="brush: csharp;">
[Given(@&quot;I visit the Pi\.NET website&quot;)]
public void GivenIVisitThePiWebsite() {
    Browser.Session.Visit(string.Format(&quot;/&quot;));
}
</pre></p>
<p>Using Coypu, I&#8217;m going to open the website specified in the CoypuInitializer class and visit the root of that website.</p>
<p>I now go to my MVC app and implement just enough to get that step passing.</p>
<p>Once I&#8217;ve done that, running the tests now gives:</p>
<p><pre class="brush: plain;">

Given I visit the Pi.NET website
-&gt; done: PiNetSteps.GivenIVisitThePiWebsite() (15.4s)
And I have selected the 'Bucknall Big Number' algorithm
-&gt; pending: PiNetSteps.GivenIHaveSelectedTheBucknallBigNumberAlgorithm(&quot;Bucknall Big Number&quot;)

</pre></p>
<p>i.e. &#8211; the first step has completed and the test has stopped at the next pending step. We&#8217;ve successfully hit the website.</p>
<p>I proceed like this, step by step, until I end up with the following steps file. I&#8217;ve added comments to explain the Coypu features I am using:</p>
<p><pre class="brush: csharp;">
[Binding]
public class PiNetSteps:Steps {
    private string numberOfDecimalPlaces;

    [Given(@&quot;I have selected the '(.+)' algorithm&quot;)]
    public void GivenIHaveSelectedAnAlgorithm(string algorithm) {
        //pass on this call to the generic radio button method (later in this class)
        Given(string.Format(&quot;I select the radio button '{0}'&quot;, algorithm));
    }

    [Given(@&quot;I have entered (.+) decimal places&quot;)]
    public void GivenIHaveEnteredTheNumberOfRequiredDecimalPlaces(string numberOfDecimalPlaces) {
        this.numberOfDecimalPlaces = numberOfDecimalPlaces; //store for later use in an assert
        //populate a text box
        Browser.Session.FillIn(&quot;NumberOfDecimalPlaces&quot;).With(numberOfDecimalPlaces);
    }

    [When(@&quot;I press Go&quot;)]
    public void WhenIPressGo() {
        //click a link. This fires an AJAX post to controller action
        //(I wanted to test JS capabilities of Selenium headless browser)
        Browser.Session.ClickLink(&quot;Calculate&quot;);
    }

    [Then(@&quot;Pi should be displayed to the correct number of decimal places&quot;)]
    public void ThenPiShouldBeDisplayedToTheRequestedNumberOfDecimalPlaces() {
        //Check page HasContent I'm after - &quot;Number of iterations&quot; is displayed by AJAX call result
        if (Browser.Session.HasContent(&quot;Number of iterations:&quot;)) {
            //check Pi is calculated to correct number of places
            string piToNumberOfRequiredDecimalPlaces = Pi.Get(Convert.ToInt32(numberOfDecimalPlaces));
            Element piElement = Browser.Session.FindField(&quot;pi&quot;); //find HTML element
            string calculatedPi = piElement.Text;
            Assert.That(piToNumberOfRequiredDecimalPlaces, Is.EqualTo(calculatedPi));
        }
        else {
            Assert.Fail(&quot;Could not find PI&quot;);
        }
    }

    [Then(@&quot;Calculation statistics should be displayed&quot;)]
    public void ThenCalculationStatisticsShouldBeDisplayed() {
        //you can use actions/funcs with different retry timeouts
        Assert.IsTrue(Browser.Session.WithIndividualTimeout(TimeSpan.FromMilliseconds(1),
                       () =&gt; Browser.Session.HasContent(&quot;Number of iterations: &quot;)),
                       &quot;Number of Iterations taken not found&quot;);
        Assert.IsTrue(Browser.Session.WithIndividualTimeout(TimeSpan.FromMilliseconds(1),
                       () =&gt; Browser.Session.HasContent(&quot;Number of decimal places: &quot; + numberOfDecimalPlaces)),
                       &quot;Number of Decimal places calculated not found&quot;);
        Assert.IsTrue(Browser.Session.WithIndividualTimeout(TimeSpan.FromMilliseconds(1),
                       () =&gt; Browser.Session.HasContent(&quot;Elapsed Milliseconds: &quot;)),
                       &quot;Time taken not found&quot;);
    }

    [Given(@&quot;I select the radio button '(.+)'&quot;)]
    public void SelectARadioButton(string radioButtonValue) {
        //select a radio button by value
        Browser.Session.Choose(radioButtonValue);
    }

    [Given(@&quot;I visit the Pi.NET website&quot;)]
    public void GivenIVisitThePiPage() {
        //visit a web page at site specified in Coypu initialization.
        Browser.Session.Visit(string.Format(&quot;/&quot;));
    }
}
</pre></p>
<p>I&#8217;ve used several SpecFlow and Coypu features in the class above. There are many more that you can read about at the <a href="https://github.com/ITV/Coypu">GitHub Coypu website</a>, or the README.md file that comes with the Coypu binaries. The documentation also shows how to use a real browser, rather than the Selenium headless one.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/733/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/733/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/733/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/733/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/733/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/733/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/733/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/733/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/733/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/733/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/733/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/733/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/733/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/733/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=733&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/08/23/bdd-with-specflow-and-coypu-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>
	</item>
		<item>
		<title>BDD with SpecFlow and Coypu (Part 1)</title>
		<link>http://kashfarooq.wordpress.com/2011/08/19/bdd-with-specflow-and-coypu-part-1/</link>
		<comments>http://kashfarooq.wordpress.com/2011/08/19/bdd-with-specflow-and-coypu-part-1/#comments</comments>
		<pubDate>Fri, 19 Aug 2011 10:40:51 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Behaviour Driven Development]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Coypu]]></category>
		<category><![CDATA[SpecFlow]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=706</guid>
		<description><![CDATA[I&#8217;ve been doing TDD for years and I thought it was about time I got into BDD too. I&#8217;m going to use BDD to add a UI in front of the various implementations of Pi calculation algorithms I&#8217;ve been working on. This post will describe what you need to install and how to get a SpecFlow feature [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=706&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing TDD for years and I thought it was about time I got into BDD too.</p>
<p>I&#8217;m going to use BDD to add a UI in front of the <a href="http://kashfarooq.wordpress.com/tag/pi/">various implementations of Pi calculation algorithms</a> I&#8217;ve been working on.</p>
<p>This post will describe what you need to install and how to get a SpecFlow feature file running via NUnit.</p>
<h3>Prerequisites</h3>
<p><strong></strong><span style="text-decoration:underline;">Headless browser:</span></p>
<p>Firing up a real browser from a BDD test can be slow. So, I&#8217;m using the Selenium headless Java browser.</p>
<p>Download <a href="http://code.google.com/p/selenium/downloads/detail?name=selenium-server-standalone-2.4.0.jar&amp;can=2&amp;q=">selenium-server-standalone-2.4.0.jar</a> (and, of course, you need <a href="http://www.java.com/en/download/">Java</a>)</p>
<p>To start it up:</p>
<p><pre class="brush: plain;">

java -jar selenium-server-standalone-2.3.0.jar

</pre></p>
<p><span style="text-decoration:underline;">SpecFlow:</span></p>
<p>Install <a href="http://specflow.org/downloads/installer.aspx">SpecFlow</a> with the full installer and it will integrate with Dev Studio.</p>
<p>You can keep your feature files in your solution and SpecFlow will automatically generate NUnit based code-behind files.</p>
<p>I also recommend you watch the <a href="http://www.specflow.org/specflow/screencast.aspx">SpecFlow Screen Cast</a> &#8211; an excellent introduction to quickly get you up and running.</p>
<p><span style="text-decoration:underline;">Coypu</span></p>
<p>To get my SpecFlow BDD tests to interact with the browser, I&#8217;m using <a href="https://github.com/featurist/Coypu">Coypu</a>.</p>
<p>Coypu is:</p>
<blockquote><p><em>A more intuitive DSL for interacting with the browser in the way a human being would, inspired by the ruby framework Capybara.</em></p></blockquote>
<p><em></em><span style="text-decoration:underline;">Other software</span></p>
<p>You need NUnit (as SpecFlow creates NUnit tests).</p>
<h3>Adding the first feature file</h3>
<p>I&#8217;ve already got a few implementations of algorithms to calculate Pi. I just want a simple UI that allows you to select an algorithm, type how many decimal places you want Pi calculated to, and then hit &#8220;Calculate&#8221;. I want the &#8220;Calculate&#8221; link/button to call back to my application via AJAX (I want to see how the headless browser copes with Javascript).</p>
<p><span style="text-decoration:underline;">Step 1: Add a feature file</span></p>
<p>A feature file is just a text file that describes the functionality you want to implement. It has a simple Given-When-Then structure that should be understandable by non-developers. Hence, they could be created by Business Analysts, etc.</p>
<p>I created a new class library called Spec and added a feature file using the &#8220;Add New Item&#8221; Dev Studio menu. You&#8217;ll see the option &#8220;SpecFlow Feature File&#8221;.</p>
<p><pre class="brush: plain;">
Feature: Calculate Pi using various algorithms
	I want to be able to view Pi to varying decimal places

Scenario: Display Pi using Taylor series and Bucknall's BigNumber to many decimal places
	Given I visit the Pi.NET website
	And I have selected the 'Bucknall Big Number' algorithm
	And I have entered 500 decimal places
	When I press Go
	Then Pi should be displayed to the correct number of decimal places
	And Calculation statistics should be displayed

</pre></p>
<p>You&#8217;ll also need to add DLL references to TechTalk.SpecFlow.dll and nunit.framework.dll</p>
<p>Once you&#8217;ve done this, compile and run all the unit tests in your Spec class library. You&#8217;ll see output like this:</p>
<p><pre class="brush: plain;">

Given I visit the Pi.NET website
-&gt; No matching step definition found for the step. Use the following code to create one:
[Binding]
public class StepDefinitions {
   [Given(@&quot;I visit the Pi\.NET website&quot;)]
   public void GivenIVisitThePi_NETWebsite()
   {
       ScenarioContext.Current.Pending();
   }
}
etc, etc.
</pre></p>
<p>SpecFlow has told you exactly what you need to do.</p>
<p>So, let&#8217;s copy and paste the code into a new C# file called PiNetSteps:</p>
<p><pre class="brush: csharp;">
[Binding]
public class PiNetSteps {
    [Given(@&quot;I visit the Pi\.NET website&quot;)]
    public void GivenIVisitThePi_NETWebsite() {
        ScenarioContext.Current.Pending();
    }

    [Given(@&quot;I have selected the 'Bucknall Big Number' algorithm&quot;)]
    public void GivenIHaveSelectedTheBucknallBigNumberAlgorithm() {
        ScenarioContext.Current.Pending();
    }

    [Given(@&quot;I have entered 500 decimal places&quot;)]
    public void GivenIHaveEntered500DecimalPlaces() {
        ScenarioContext.Current.Pending();
    }

    [When(@&quot;I press Go&quot;)]
    public void WhenIPressGo() {
        ScenarioContext.Current.Pending();
    }

    [Then(@&quot;Pi should be displayed to the correct number of decimal places&quot;)]
    public void ThenPiShouldBeDisplayedToTheCorrectNumberOfDecimalPlaces() {
        ScenarioContext.Current.Pending();
    }

    [Then(@&quot;Calculation statistics should be displayed&quot;)]
    public void ThenCalculationStatisticsShouldBeDisplayed() {
        ScenarioContext.Current.Pending();
    }
}
</pre></p>
<p>Now when you run the unit tests you get the output:</p>
<p><pre class="brush: plain;">

Ignored: One or more step definitions are not implemented yet.

</pre></p>
<p>We can improve the steps code by parameterizing it with Regex. For example, rather than hard coding &#8220;500 decimal places&#8221;, let&#8217;s make this a parameter. And the algorithm name can also be a parameter.</p>
<p>Making these changes gives:</p>
<p><pre class="brush: csharp;">
[Given(@&quot;I have selected the '(.+)' algorithm&quot;)]
public void GivenIHaveSelectedAnAlgorithm(string algorithm) {
    ScenarioContext.Current.Pending();
}

[Given(@&quot;I have entered '(.+)' decimal places&quot;)]
public void GivenIHaveEnteredTheRequiredNumberOfDecimalPlaces(int numberOfDecimalPlaces) {
    this.numberOfDecimalPlaces = numberOfDecimalPlaces; //store for a later assert
    ScenarioContext.Current.Pending();
}
</pre></p>
<p>We&#8217;re now at a stage that opens up lots of possibilities. You&#8217;ve gone from a feature file to a C# class and you now have options on how deep you want your tests to go. If you system under test is not a web application, you are ready to start implementing it straight away. If your system has lots of external dependencies that are not under your control, you could easily stub them out with a container. Or perhaps you want your tests to go through all the application layers and hit a database or webservice. You could easily introduce test database and webservices if you wish.</p>
<p>In the <a href="http://kashfarooq.wordpress.com/2011/08/23/bdd-with-specflow-and-coypu-part-2/">next post I&#8217;ll get Coypu up and running</a> and use it to get my SpecFlow steps class to hit the Selenium headless browser.</p>
<p>Next: <a href="http://kashfarooq.wordpress.com/2011/08/23/bdd-with-specflow-and-coypu-part-2/">BDD with SpecFlow and Coypu (Part 2)</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/706/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/706/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/706/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/706/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/706/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/706/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/706/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/706/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/706/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/706/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/706/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/706/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/706/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/706/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=706&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/08/19/bdd-with-specflow-and-coypu-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>
	</item>
		<item>
		<title>Calculating Pi in C# part 3 &#8211; using the BigRational class</title>
		<link>http://kashfarooq.wordpress.com/2011/08/01/calculating-pi-in-c-part-3-using-the-net-4-bigrational-class/</link>
		<comments>http://kashfarooq.wordpress.com/2011/08/01/calculating-pi-in-c-part-3-using-the-net-4-bigrational-class/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 20:33:31 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[BigRational]]></category>
		<category><![CDATA[Pi]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=682</guid>
		<description><![CDATA[In an earlier post I ported a Java implementation of a Pi calculator &#8211; my port used the BigInteger class that lives in the System.Numerics assembly of .NET 4. I also performance tested my port against an implementation by Julian M Bucknall that used his own BigNumber class. Julian&#8217;s implementation won that performance test, coming in at an [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=682&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In an earlier post I <a href="http://kashfarooq.wordpress.com/2011/07/23/calculating-pi-in-c-part-2-using-the-net-4-biginteger-class/">ported a Java implementation of a Pi calculator</a> &#8211; my port used the BigInteger class that lives in the System.Numerics assembly of .NET 4. I also performance tested my port against an <a href="http://www.boyet.com/Articles/PiCalculator.html">implementation</a> by Julian M Bucknall that used his own BigNumber class. Julian&#8217;s implementation won that performance test, coming in at an impressive 70-80 milliseconds to calculate Pi to 1000 decimal places.</p>
<p>Now it is time for me to try an implementation alone!</p>
<p>I&#8217;m going to use the following John Machin formula:</p>
<p><img class="aligncenter size-full wp-image-662" title="John Machin's Pi formula" src="http://kashfarooq.files.wordpress.com/2011/07/johnmachin_pi.png" alt="John Machin's Pi formula" width="248" height="81" />Arctan can be calculated using the following Taylor series:</p>
<p><img class="aligncenter size-full wp-image-685" title="ArcTan calculated using the Taylor Series" src="http://kashfarooq.files.wordpress.com/2011/08/arctantaylorseries.png" alt="ArcTan calculated using the Taylor Series" width="353" height="53" />Rather than creating arbitrarily big numbers with BigInteger, I need to create numbers with arbitrarily large precision.   I need a BigRational. And one exists, but it did not make it into the .NET 4 framework. You can <a href="http://bcl.codeplex.com/releases/view/42782">download BigRational form CodePlex</a>.</p>
<p>So, here is my implementation of arctan:</p>
<p><pre class="brush: csharp;">
public class ArcTanWithBigRational {
    public ArcTanWithBigRational() {
        Iterations = 0;
    }

    public int Iterations;

    public BigRational Calculate(BigRational x, int maxNumberOfIterations, int precision) {
        bool doASubtract = true;
        BigRational runningTotal = x;
        int count = 0;
        var divisor = new BigInteger(3);
        while (count &lt; maxNumberOfIterations) {
            BigRational current = BigRational.Pow(x, divisor);
            current = current/divisor;
            if (doASubtract) {
                runningTotal = runningTotal - current;
            }
            else {
                runningTotal = runningTotal + current;
            }
            doASubtract = !doASubtract;
            count++;
            divisor = divisor + 2;
            if (WeHaveEnoughPrecision(current, precision)) {
                Iterations = count;
                break;
            }
        }
        return runningTotal;
    }

    private static bool WeHaveEnoughPrecision(BigRational current, int precision) {
        return current.GetFractionPart().ToString().Length &gt; precision+2; //extra 2 digits to ensure enough precision
    }
}
</pre></p>
<p>Now to perform the calculation:</p>
<p><pre class="brush: csharp;">
public string Calculate(int numberOfDigits) {
    var arcTanA = new ArcTanWithBigRational();
    var arcTanB = new ArcTanWithBigRational();
    var a = 16 * arcTanA.Calculate(BigRational.Divide(1, 5), 1000, numberOfDigits);
    var b = 4 * arcTanB.Calculate(BigRational.Divide(1, 239), 1000, numberOfDigits);
    var pi = a - b;
    return BigRationalPiFormatter.Format(pi, numberOfDigits);
}
</pre></p>
<p>And the results:</p>
<p><pre class="brush: plain;">
Precision = 1000 digits
Number of iterations = 923
Elapsed Milliseconds = 1192
</pre></p>
<p>Not bad! No where near as fast as the <a href="http://kashfarooq.wordpress.com/2011/07/23/calculating-pi-in-c-part-2-using-the-net-4-biginteger-class/">other implementations in my previous post</a>, but not too bad and with far fewer iterations.</p>
<p>I can try one final optimization to try and get my implementation running faster. I have a dual-core laptop so let&#8217;s try some Parallel Tasks:</p>
<p><pre class="brush: csharp;">
public string Calculate(int numberOfDigits) {
    var a = new ArcTanWithBigRational();
    var b = new ArcTanWithBigRational();
    Task&lt;BigRational&gt; task1 = Task&lt;BigRational&gt;.Factory.StartNew(
                            () =&gt; a.Calculate(BigRational.Divide(1, 5),1000,numberOfDigits));
    Task&lt;BigRational&gt; task2 = Task&lt;BigRational&gt;.Factory.StartNew(
                            () =&gt; b.Calculate(BigRational.Divide(1, 239), 1000, numberOfDigits));

    var pi = 16 * task1.Result - 4 * task2.Result;

    return BigRationalPiFormatter.Format(pi, numberOfDigits);
}
</pre></p>
<p>The results this time:</p>
<p><pre class="brush: plain;">
Precision = 1000 digits
Number of iterations = 923
Elapsed Milliseconds = 1099
</pre></p>
<p>A little faster, but nothing to get excited about.</p>
<p>For completeness, here is my routine to format the BigRational Pi into a string:</p>
<p><pre class="brush: csharp;">
public class BigRationalPiFormatter {
    public static string Format(BigRational pi, int numberOfDigits)
    {
        BigInteger numeratorShiftedToEnoughDigits =
                       (pi.Numerator * BigInteger.Pow(new BigInteger(10), numberOfDigits));
        var bigInteger = numeratorShiftedToEnoughDigits / pi.Denominator;
        string piToBeFormatted = bigInteger.ToString();
        var builder = new StringBuilder();
        builder.Append(piToBeFormatted[0]);
        builder.Append(&quot;.&quot;);
        builder.Append(piToBeFormatted.Substring(1, numberOfDigits));
        return builder.ToString();
    }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/682/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/682/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/682/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/682/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/682/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/682/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/682/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/682/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/682/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/682/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/682/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/682/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/682/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/682/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=682&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/08/01/calculating-pi-in-c-part-3-using-the-net-4-bigrational-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>

		<media:content url="http://kashfarooq.files.wordpress.com/2011/07/johnmachin_pi.png" medium="image">
			<media:title type="html">John Machin&#039;s Pi formula</media:title>
		</media:content>

		<media:content url="http://kashfarooq.files.wordpress.com/2011/08/arctantaylorseries.png" medium="image">
			<media:title type="html">ArcTan calculated using the Taylor Series</media:title>
		</media:content>
	</item>
		<item>
		<title>Calculating Pi in C# part 2 &#8211; using the .NET 4 BigInteger class</title>
		<link>http://kashfarooq.wordpress.com/2011/07/23/calculating-pi-in-c-part-2-using-the-net-4-biginteger-class/</link>
		<comments>http://kashfarooq.wordpress.com/2011/07/23/calculating-pi-in-c-part-2-using-the-net-4-biginteger-class/#comments</comments>
		<pubDate>Sat, 23 Jul 2011 13:36:04 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Pi]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=658</guid>
		<description><![CDATA[In my previous post, I used a couple of algorithms to calculate Pi. With my implementation of the algorithms, to get to a precision of just 6 decimal places took well over a million iterations and over 3 seconds. Clearly I was doing something wrong. A few Google searches later I found this implementation by Julian M [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=658&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://kashfarooq.wordpress.com/2011/07/17/calculating-pi-in-c-part-1/">previous post</a>, I used a couple of algorithms to calculate Pi. With my implementation of the algorithms, to get to a precision of just 6 decimal places took well over a million iterations and over 3 seconds.</p>
<p>Clearly I was doing something wrong.</p>
<p>A few Google searches later I found <a href="http://www.boyet.com/Articles/PiCalculator.html">this implementation</a> by Julian M Bucknall. In this implementation, Julian creates a BigNumber class to handle the fact that, before .NET 4, there was no way to handle numbers to many digits of precision. His class uses  <a href="http://en.wikipedia.org/wiki/Fixed-point_arithmetic">fixed point arithmetic</a> for storing data and performing calculations &#8211; effectively it works in base 4,294,967,296 (which is 2<sup>32</sup>).</p>
<p>As .NET does now contain a BigInteger class (in .NET 4&#8242;s System.Numerics), I started searching for C# implementations that used this class. I couldn&#8217;t find anything in C#, but I did find a <a href="http://research.uvu.edu/math/merrin/pi3.html">Java implementation</a> that used a BigInteger class.</p>
<p>So, I decided to port it to C#, amending the BigInteger usages to match the .NET implementation syntax.</p>
<p>The formula used is the one that <a href="http://en.wikipedia.org/wiki/John_Machin">John Machin</a> devised in 1706:</p>
<p><img class="aligncenter size-full wp-image-662" title="John Machin's Pi formula" src="http://kashfarooq.files.wordpress.com/2011/07/johnmachin_pi.png" alt="John Machin's Pi formula" width="248" height="81" />So, here is the .NET port of the Java implementation  - it includes a method called InverseTan to be used in the above formula, which I won&#8217;t even try to understand at the moment. I&#8217;m just doing the port!</p>
<p><pre class="brush: csharp;">
public class PiJavaPort {
    public static BigInteger InverseTan(int denominator, int numberOfDigitsRequired) {
        int demonimatorSquared = denominator*denominator;

        int degreeNeeded = GetDegreeOfPrecisionNeeded(demonimatorSquared, numberOfDigitsRequired);

        BigInteger tenToNumberPowerOfDigitsRequired = GetTenToPowerOfNumberOfDigitsRequired(numberOfDigitsRequired);

        int c = 2*degreeNeeded + 1;
        BigInteger s = BigInteger.Divide(tenToNumberPowerOfDigitsRequired, new BigInteger(c)); // s = (10^N)/c
        for (int i = 0; i &lt; degreeNeeded; i++) {
            c = c - 2;
            var temp1 = BigInteger.Divide(tenToNumberPowerOfDigitsRequired, new BigInteger(c));
            var temp2 = BigInteger.Divide(s, new BigInteger(demonimatorSquared));
            s = BigInteger.Subtract(temp1, temp2);
        }
        Console.WriteLine(&quot;Number of iterations=&quot; + degreeNeeded);

        // return s/denominator, which is integer part of 10^numberOfDigitsRequired times arctan(1/k)
        return BigInteger.Divide(s, new BigInteger(denominator));

    }

    private static int GetDegreeOfPrecisionNeeded(int demonimatorSquared, int numberOfDigitsRequired) {
        //the degree of the Taylor polynomial needed to achieve numberOfDigitsRequired
        //digit accuracy of arctan(1/denominator).
        int degreeNeeded = 0;

        while ((Math.Log(2*degreeNeeded + 3) + (degreeNeeded + 1)*Math.Log10(demonimatorSquared))
                                                &lt;= numberOfDigitsRequired*Math.Log(10)) {
            degreeNeeded++;
        }
        return degreeNeeded;
    }

    private static BigInteger GetTenToPowerOfNumberOfDigitsRequired(int numberOfDigitsRequired) {
        var tenToNumberOfDigitsRequired = new BigInteger(1);

        //  The following loop computes 10^numberOfDigitsRequired
        for (var i = 0; i &lt; numberOfDigitsRequired; i++) {
            tenToNumberOfDigitsRequired = BigInteger.Multiply(tenToNumberOfDigitsRequired, new BigInteger(10));
        }
        return tenToNumberOfDigitsRequired;
    }
}
</pre></p>
<p>Finally, we need a method to put it all together &#8211; we need to implement the Machin formula:</p>
<p><pre class="brush: csharp;">
public static string Calculate(int numberOfDigitsRequired)
{
    numberOfDigitsRequired += 8; //  To be safe, compute 8 extra digits, to be dropped at end. The 8 is arbitrary

    var a = BigInteger.Multiply(InverseTan(5, numberOfDigitsRequired), new BigInteger(16)); //16 x arctan(1/5)
    var b = BigInteger.Multiply(InverseTan(239, numberOfDigitsRequired), new BigInteger(4)); //4 x arctan(1/239)

    BigInteger pi = BigInteger.Subtract(a, b);

    var piAsString = BigInteger.Divide(pi, new BigInteger(100000000)).ToString();
    var piFormatted = piAsString[0]+&quot;.&quot;+piAsString.Substring(1,numberOfDigitsRequired-8);
    return piFormatted;
}
</pre></p>
<p>Now to test the two implementations for performance &#8211; my Java port above vs. <a href="http://www.boyet.com/Articles/PiCalculator.html">Julian M Bucknall</a> implementation using his own BigNumber class.</p>
<p>First, my Java Port using .NET&#8217;s numerics:</p>
<p><pre class="brush: plain;">
Precision = 1000 digits
Number of iterations needed = 3659
Elapsed Milliseconds = 96
</pre></p>
<p>Not bad! Much better than 1 million plus iterations for 6 decimal places that my pathetic attempt took!</p>
<p>Now to Julian M Bucknall&#8217;s implementation (using his own BigNumber class):</p>
<p><pre class="brush: plain;">
Precision = 1000 digits
Number of iterations needed = 1603
Elapsed Milliseconds = 77
</pre></p>
<p>We have a winner.</p>
<p>Julian&#8217;s BigNumber class is optimised for this calculation &#8211; it can only divide a BigNumber by an integer. You cannot divide a BigNumber by another BigNumber. He states that if he had to implement such functionality he &#8220;would have discretely dropped the entire project&#8221;!</p>
<p>BigInteger does not have this limitation (and this functionality is used in the port).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/658/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/658/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/658/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=658&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/07/23/calculating-pi-in-c-part-2-using-the-net-4-biginteger-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>

		<media:content url="http://kashfarooq.files.wordpress.com/2011/07/johnmachin_pi.png" medium="image">
			<media:title type="html">John Machin&#039;s Pi formula</media:title>
		</media:content>
	</item>
		<item>
		<title>Calculating Pi in C# with series algorithms</title>
		<link>http://kashfarooq.wordpress.com/2011/07/17/calculating-pi-in-c-part-1/</link>
		<comments>http://kashfarooq.wordpress.com/2011/07/17/calculating-pi-in-c-part-1/#comments</comments>
		<pubDate>Sun, 17 Jul 2011 12:36:04 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Pi]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=599</guid>
		<description><![CDATA[People write applications to calculate Pi to thousands of decimal places &#8211; I decided to investigate how they do that. Google took me to a post discussing using recursion to calculate Pi. Quite ironic considering the post is on Stack Overflow&#8230; Anyway, the post did provide me with plenty of links and algorithm names for me [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=599&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>People write applications to calculate Pi to thousands of decimal places &#8211; I decided to investigate how they do that.</p>
<p>Google took me to a post discussing <a href="http://stackoverflow.com/questions/39395/how-do-i-calculate-pi-in-c">using recursion to calculate Pi</a>. Quite ironic considering the post is on Stack Overflow&#8230; Anyway, the post did provide me with plenty of links and algorithm names for me to refine my search and find a way to do it without recursion.</p>
<p>I soon found this: <a href="http://numbers.computation.free.fr/Constants/Pi/piSeries.html">a collection of series algorithms to calculate Pi</a>.</p>
<p>So, I picked an algorithm and started coding.</p>
<p>To get going quickly, I decided to just use the built in .NET value types (i.e. decimal, double). These clearly are not good enough if you want to calculate Pi to hundreds of decimal places, but they would do for now.</p>
<p>To check my algorithm implementation worked, I got <a href="http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html">Pi to a few thousand decimal places from the interweb </a>:</p>
<p><pre class="brush: csharp;">
public static class Pi {
    public const string PiAsString = &quot;3.14159265358979323846264338327...etc&quot;;
    public static string Get(int numberOfDecimalPlaces) {
        return PiAsString.Substring(0, numberOfDecimalPlaces + 2);
    }
}
</pre></p>
<h3><span style="text-decoration:underline;">Leibniz-Gregory-Madhava Series</span></h3>
<p>You can calculate Pi using the following:</p>
<p><img class="aligncenter size-full wp-image-606" title="Leibniz-Gregory-Madhava" src="http://kashfarooq.files.wordpress.com/2011/07/leibniz-gregory-madhava.png" alt="" width="233" height="51" /></p>
<p>In the code below, my base class property &#8220;PiCalculatedToRequiredPrecision&#8221; is, as the name suggests, there stop if I&#8217;ve reached my target number of digits. The &#8220;KeepGoing&#8221; property is used to bail out of the loop if I&#8217;ve done far too many iterations (which I keep track of in the Iteration property) and I have still not managed to get the required number of digits.</p>
<p><pre class="brush: csharp;">
public class LeibnizGregoryMadhava:SeriesAlgorithmBase {
    public LeibnizGregoryMadhava(int numberOfDecimalPlaces) : base(numberOfDecimalPlaces) {}

    // Pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 .....

    public override decimal Calculate() {
        CurrentPi = 1;
        var multiplier = 1;
        var nextNumber = 3;

        decimal result = 1;
        while (KeepGoing) {
            multiplier = multiplier * -1;
            result = result + multiplier * (decimal)1 /(nextNumber);
            CurrentPi = result*4;
            if (PiCalculatedToRequiredPrecision)
            {
                break;
            }
            Iteration++;
            nextNumber += 2;
        }
        return CurrentPi;
    }
}
</pre></p>
<p>And now to run my algorithm a few times specifying a different precision each time:</p>
<p><pre class="brush: plain;">
LeibnizGregoryMadhava took 117 iterations and 6 milliseconds to calculate PI to 2 decimal places
LeibnizGregoryMadhava took 1686 iterations and 3 milliseconds to calculate PI to 3 decimal places
LeibnizGregoryMadhava took 10792 iterations and 22 milliseconds to calculate PI to 4 decimal places
LeibnizGregoryMadhava took 136119 iterations and 290 milliseconds to calculate PI to 5 decimal places
LeibnizGregoryMadhava took 1530010 iterations and 3358 milliseconds to calculate PI to 6 decimal places
</pre></p>
<p>Over 1.5 million iterations (and 3.4 seconds) to get to 6 decimal places!!</p>
<p>Time to try another algorithm.</p>
<h3><span style="text-decoration:underline;">Euler Series</span></h3>
<p><img class="aligncenter size-full wp-image-605" title="Euler" src="http://kashfarooq.files.wordpress.com/2011/07/euler.png" alt="" width="190" height="53" /></p>
<p><pre class="brush: csharp;">
public class Euler:SeriesAlgorithmBase {
    //pi^2 / 6 = 1 + 1/4 + 1/9 + ..... + 1/k^2

    public Euler(int numberOfDecimalPlaces) : base(numberOfDecimalPlaces) {}
    public override decimal Calculate() {
        decimal result = 0;
        Iteration = 1;
        while (KeepGoing)
        {
            long squared = Iteration * Iteration;
            result = result + (decimal)1/squared;
            CurrentPi = (decimal) Math.Sqrt((double) (result * 6));
            if (PiCalculatedToRequiredPrecision())
            {
                break;
            }
            Iteration++;
        }
        return CurrentPi;

    }
}
</pre></p>
<p>And the results:</p>
<p><pre class="brush: plain;">
Euler took 600 iterations and 74 milliseconds to calculate PI to 2 decimal places
Euler took 1611 iterations and 3 milliseconds to calculate PI to 3 decimal places
Euler took 10307 iterations and 22 milliseconds to calculate PI to 4 decimal places
Euler took 359863 iterations and 819 milliseconds to calculate PI to 5 decimal places
Euler took 1461054 iterations and 3319 milliseconds to calculate PI to 6 decimal places
</pre></p>
<p>Hmmm. Fewer iterations (just!) and 3.3 seconds to get to 6 decimal places.</p>
<p>I&#8217;m not going to break any world records with this code. Clearly I need to do more research.</p>
<p>To be continued.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/599/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/599/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/599/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=599&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/07/17/calculating-pi-in-c-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>

		<media:content url="http://kashfarooq.files.wordpress.com/2011/07/leibniz-gregory-madhava.png" medium="image">
			<media:title type="html">Leibniz-Gregory-Madhava</media:title>
		</media:content>

		<media:content url="http://kashfarooq.files.wordpress.com/2011/07/euler.png" medium="image">
			<media:title type="html">Euler</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting started with Git Source Control (and carrying code around on a USB)</title>
		<link>http://kashfarooq.wordpress.com/2011/07/10/getting-started-with-git-source-control-and-carrying-code-around-on-a-usb/</link>
		<comments>http://kashfarooq.wordpress.com/2011/07/10/getting-started-with-git-source-control-and-carrying-code-around-on-a-usb/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 13:39:14 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[Git Source Control]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Source Control]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=589</guid>
		<description><![CDATA[I&#8217;m just starting out with Git (on Windows), so I thought I&#8217;d blog about it at the same time. I downloaded and installed the msysgit version from here: http://code.google.com/p/msysgit/downloads/list. After installation is complete, create a directory for your source code and initialise a Git repository there: Now, add some code/directories to c:\dev\git-repo. You may also want [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=589&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m just starting out with Git (on Windows), so I thought I&#8217;d blog about it at the same time.</p>
<p>I downloaded and installed the msysgit version from here: <a href="http://code.google.com/p/msysgit/downloads/list">http://code.google.com/p/msysgit/downloads/list</a>.</p>
<p>After installation is complete, create a directory for your source code and initialise a Git repository there:</p>
<p><pre class="brush: plain;">
md c:\dev\git-repo
cd c:\dev\git-repo
git init
</pre></p>
<p>Now, add some code/directories to c:\dev\git-repo.<br />
You may also want to add a .gitignore file to exclude files you don&#8217;t want to check in:  here is <a href="http://kashfarooq.wordpress.com/2011/07/10/git-ignoring-files/">my .NET development .gitignore file</a>.</p>
<p>When you&#8217;re done, add them to your Git repository and commit your changes:</p>
<p><pre class="brush: plain;">
git add .  &lt;-- this adds all files beneath this level. Hence why you may want a .gitignore file.
git commit -m &quot;Initial commit&quot;
</pre></p>
<p>Now, so that you can carry your code around on a USB drive, do the following (where g: is my USB drive):</p>
<p><pre class="brush: plain;">
g:
md dev
cd dev
git clone --bare c:\dev\git-repo
</pre></p>
<p>You&#8217;ll see a message like:<br />
<pre class="brush: plain;">
Cloning into bare repository git-repo.git...
done.
</pre></p>
<p>The &#8220;bare&#8221; command leaves you with a Git repository without your files and directories. If you want to work on them you need to do the following (on say, your other computer):</p>
<p><pre class="brush: plain;">
c:
md dev
cd dev
git clone G:\dev\git-repo.git
</pre></p>
<p>Note: the last git clone was without the &#8220;bare&#8221; command &#8211; so your files will get extracted out of your USB repository and are available to work on.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/589/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/589/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/589/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=589&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/07/10/getting-started-with-git-source-control-and-carrying-code-around-on-a-usb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>
	</item>
		<item>
		<title>Git: Ignoring files for .NET development</title>
		<link>http://kashfarooq.wordpress.com/2011/07/10/git-ignoring-files/</link>
		<comments>http://kashfarooq.wordpress.com/2011/07/10/git-ignoring-files/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 13:12:05 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[Git Source Control]]></category>
		<category><![CDATA[Git]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=590</guid>
		<description><![CDATA[Here is the .gitignore file I use for .NET/C# development. Add this file to the root of your Git repository so you don&#8217;t end up adding ReSharper files, bin folders, etc to your commits:<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=590&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Here is the .gitignore file I use for .NET/C# development. Add this file to the root of your Git repository so you don&#8217;t end up adding ReSharper files, bin folders, etc to your commits:</p>
<p><pre class="brush: plain;">
obj
bin
_ReSharper.*
*.csproj.user
*.resharper.user
*.resharper
*.suo
*.cache
~$*
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/590/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/590/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/590/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=590&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/07/10/git-ignoring-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating .NET objects from JSON using DataContractJsonSerializer</title>
		<link>http://kashfarooq.wordpress.com/2011/01/31/creating-net-objects-from-json-using-datacontractjsonserializer/</link>
		<comments>http://kashfarooq.wordpress.com/2011/01/31/creating-net-objects-from-json-using-datacontractjsonserializer/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 08:26:18 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Programmatically searching]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=578</guid>
		<description><![CDATA[Creating .NET objects from JSON using DataContract and DataMember In a previous post and demonstraed that the RESTful Google Search API returns data as JSON. I needed a way to convert the JSON data into .NET objects and this post shows what I ended up with. Here is an example of the JSON result set [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=578&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div>
<div>
<div>
<p>Creating .NET objects from JSON using DataContract and DataMember</p>
<p>In a previous post and demonstraed that the RESTful Google Search API returns data as JSON. I needed a way to convert the JSON data into .NET objects and this post shows what I ended up with.</p>
<p>Here is an example of the JSON result set returned:</p>
<p><pre class="brush: plain;">
{&quot;responseData&quot;:
 {&quot;results&quot;:
 [
  {
  &quot;GsearchResultClass&quot;:&quot;GwebSearch&quot;,
  &quot;unescapedUrl&quot;:&quot;http://www.google.com/help/features.html&quot;,
  &quot;url&quot;:&quot;http://www.google.com/help/features.html&quot;,
  &quot;visibleUrl&quot;:&quot;www.google.com&quot;,
  &quot;cacheUrl&quot;:&quot;http://www.google.com/search?q\u003dcache:BNRWhS8EKYAJ:www.google.com&quot;,
  &quot;title&quot;:&quot;\u003cb\u003eSearch\u003c/b\u003e Features - \u003cb\u003eGoogle\u003c/b\u003e&quot;,
  &quot;titleNoFormatting&quot;:&quot;Search Features - Google&quot;,
  &quot;content&quot;:&quot;To find reviews and showtimes....&quot;
  },
  {
  &quot;GsearchResultClass&quot;:&quot;GwebSearch&quot;,
  etc
  },
  etc
 ],
 &quot;cursor&quot;: {
 &quot;pages&quot;: [
  { &quot;start&quot;: &quot;0&quot;, &quot;label&quot;: 1 },
  { &quot;start&quot;: &quot;8&quot;, &quot;label&quot;: 2 },
  etc
  { &quot;start&quot;: &quot;56&quot;,&quot;label&quot;: 8 }
  ],
  &quot;estimatedResultCount&quot;: &quot;59600000&quot;,
  &quot;currentPageIndex&quot;: 0,
  &quot;moreResultsUrl&quot;: &quot;http://www.google.com/search?oe=utf8&amp;ie=utf8&amp;source=uds&amp;start=0&amp;hl=en&amp;q=MY SEARCH TEXT&quot;
  }
 },
 &quot;responseDetails&quot;: null,
 &quot;responseStatus&quot;: 200
}
</pre></p>
<p>We can use System.Runtime.Serialization to create .NET objects from this JSON data.</p>
<p>For example, the top level JSON responseData can be represented by the following .NET type:</p>
<p><pre class="brush: csharp;">
[DataContract]
public class GoogleSearchResults {
  [DataMember(Name = &quot;responseData&quot;)]
  public ResponseData ResponseData { get; set; }
}
</pre></p>
<p>Note that I&#8217;ve specified the Name attribute. Without it I would have had to have a property called &#8220;responseData&#8221; rather than &#8220;ResponseData&#8221;.</p>
<p>The rest of the data is extracted using the classes below. Note that I can be quite selective in what data I wanted to transfer from JSON to .NET. If I don&#8217;t need, say, the &#8220;cacheUrl&#8221;, I can just omit it from my .NET objects. I can also rename data. I have put the data from &#8220;titleNoFormatting&#8221; into a property called Title:</p>
<p><pre class="brush: csharp;">
[DataContract]
public class ResponseData
{
  [DataMember(Name=&quot;results&quot;)]
  public IEnumerable&lt;Result&gt; Results { get; set; }

  [DataMember(Name = &quot;cursor&quot;)]
  public Cursor Cursor { get; set; }
}

[DataContract]
public class Cursor
{
  [DataMember(Name = &quot;moreResultsUrl&quot;)]
  public string MoreResultsUrl { get; set; }

  [DataMember(Name = &quot;pages&quot;)]
  public IEnumerable&lt;Page&gt; Pages { get; set; }
}

[DataContract]
public class Result
{
  [DataMember(Name = &quot;url&quot;)]
  public string Url { get; set; }

  [DataMember(Name = &quot;titleNoFormatting&quot;)]
  public string Title { get; set; }
}

[DataContract]
public class Page
{
  [DataMember(Name = &quot;start&quot;)]
  public int Start { get; set; }

  [DataMember(Name = &quot;label&quot;)]
  public string Label { get; set; }
}
</pre></p>
<p>Finally, I need a method to actually deserialize a JSON string into my .NET objects. I can use System.Runtime.Serialization.Json.DataContractJsonSerializer to do this. I have created the following generic method that takes a JSON string and the type I want it to be deserialised into, and then returns an instantiated .NET object:</p>
<p><pre class="brush: csharp;">
public static T Deserialise&lt;T&gt;(string json) {
  var obj = Activator.CreateInstance&lt;T&gt;();
  using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json))) {
    var serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T) serializer.ReadObject(memoryStream);
    return obj;
  }
}
</pre></p>
<p>This generic method can then be used to convert a JSON string to the specified .NET type:</p>
<p><pre class="brush: csharp;">
string reponseJson=GetJsonDataFromGoogle(&quot;MY SEARCH TERM);
results = Deserialise&lt;GoogleSearchResults&gt;(responseJson);
foreach (var googleSearchResult in results.ResponseData.Results) {
  Console.WriteLine(googleSearchResult.Url);
}
</pre></p>
</div>
</div>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/578/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=578&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/01/31/creating-net-objects-from-json-using-datacontractjsonserializer/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>
	</item>
		<item>
		<title>Programmatically searching Google (Part 2): Using the RESTful interface</title>
		<link>http://kashfarooq.wordpress.com/2011/01/30/programatically-searching-google-part-2-using-the-restful-interface/</link>
		<comments>http://kashfarooq.wordpress.com/2011/01/30/programatically-searching-google-part-2-using-the-restful-interface/#comments</comments>
		<pubDate>Sun, 30 Jan 2011 13:35:04 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Programmatically searching]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=563</guid>
		<description><![CDATA[This post follows on from part 1, in which I perform a Google search using the .NET wrapper library project. I was curious why the library didn&#8217;t appear to provide any paging functionality and seemed to just get all the search results in one hit. So, I&#8217;m now going to look at searching directly using [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=563&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This post follows on from part 1, in which I perform a <a href="http://kashfarooq.wordpress.com/2011/01/24/programmatically-searching-google-part-1-the-google-api-for-net/">Google search using the .NET wrapper library project</a>. I was curious why the library didn&#8217;t appear to provide any paging functionality and seemed to just get all the search results in one hit.</p>
<p>So, I&#8217;m now going to look at searching directly using Google&#8217;s RESTful API.</p>
<p>The URL that you hit is:</p>
<p>http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;q=MY SEARCH TEXT&amp;rsz=large&amp;key=MY GOOGLE KEY&amp;start=0</p>
<p>You can omit the key, but Google recommends you provide it.</p>
<p>This returns a JSON result set like the following.</p>
<p><em>[Note: also see "<a href="http://kashfarooq.wordpress.com/2011/01/31/creating-net-objects-from-json-using-datacontractjsonserializer/">Creating .NET objects from JSON using DataContractJsonSerializer</a>"]</em></p>
<p><pre class="brush: plain;">
{&quot;responseData&quot;:
 {&quot;results&quot;:
 [
  {
  &quot;GsearchResultClass&quot;:&quot;GwebSearch&quot;,
  &quot;unescapedUrl&quot;:&quot;http://www.google.com/help/features.html&quot;,
  &quot;url&quot;:&quot;http://www.google.com/help/features.html&quot;,
  &quot;visibleUrl&quot;:&quot;www.google.com&quot;,
  &quot;cacheUrl&quot;:&quot;http://www.google.com/search?q\u003dcache:BNRWhS8EKYAJ:www.google.com&quot;,
  &quot;title&quot;:&quot;\u003cb\u003eSearch\u003c/b\u003e Features - \u003cb\u003eGoogle\u003c/b\u003e&quot;,
  &quot;titleNoFormatting&quot;:&quot;Search Features - Google&quot;,
  &quot;content&quot;:&quot;To find reviews and showtimes....&quot;
  },
  {
  &quot;GsearchResultClass&quot;:&quot;GwebSearch&quot;,
  etc
  },
  etc
 ],
 &quot;cursor&quot;: {
 &quot;pages&quot;: [
  { &quot;start&quot;: &quot;0&quot;, &quot;label&quot;: 1 },
  { &quot;start&quot;: &quot;8&quot;, &quot;label&quot;: 2 },
  etc
  { &quot;start&quot;: &quot;56&quot;,&quot;label&quot;: 8 }
  ],
  &quot;estimatedResultCount&quot;: &quot;59600000&quot;,
  &quot;currentPageIndex&quot;: 0,
  &quot;moreResultsUrl&quot;: &quot;http://www.google.com/search?oe=utf8&amp;ie=utf8&amp;source=uds&amp;start=0&amp;hl=en&amp;q=MY SEARCH TEXT&quot;
  }
 },
 &quot;responseDetails&quot;: null,
 &quot;responseStatus&quot;: 200
}
</pre></p>
<p>Now we&#8217;re getting somewhere. The &#8220;cursor&#8221; block at the bottom of the returned data provides paging information, a &#8220;moreResultsUrl&#8221;, an estimate of the number of results. Eveything we need.</p>
<p>As I have been told the number of pages (in the above example there are 8 pages) and the starting point of each page (0, 8, &#8230;, 56), I can just use my original URL again, and adjust the start parameter for each call (i.e. I don&#8217;t need to use the moreResultsUrl data provided in the cursor block).</p>
<p>So, I can just use:</p>
<p>http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;q=MY SEARCH TEXT&amp;rsz=large&amp;key=MY Google KEY&amp;start=8</p>
<p>After playing with some more searches I realised that a maximum of 8 pages were being returned each time.</p>
<p>In my example above, each page returned 8 results. 8 pages of 8 results does not give me 59600000 results!</p>
<p>I tried the following URL:</p>
<p>http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;q=MY SEARCH TEXT&amp;rsz=large&amp;start=100</p>
<p>The result returned was:</p>
<p><pre class="brush: plain;">
{&quot;responseData&quot;: null, &quot;responseDetails&quot;: &quot;out of range start&quot;, &quot;responseStatus&quot;: 400}
</pre></p>
<p>Google does not allow you to search for more than 64 results!</p>
<p>So the only way to get more than 64 results would be to screen scrape, which is ugly (but can be made more bearable by using <a href="http://developer.mindtouch.com/en/docs/SgmlReader">SGMLReader</a> and LINQ to XML). Though I&#8217;m pretty sure Google&#8217;s T&#8217;s &amp; C&#8217;s don&#8217;t allow screen scraping!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/563/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/563/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/563/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=563&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/01/30/programatically-searching-google-part-2-using-the-restful-interface/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>
	</item>
		<item>
		<title>Programmatically searching Google (Part 1): The Google API for .NET</title>
		<link>http://kashfarooq.wordpress.com/2011/01/24/programmatically-searching-google-part-1-the-google-api-for-net/</link>
		<comments>http://kashfarooq.wordpress.com/2011/01/24/programmatically-searching-google-part-1-the-google-api-for-net/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 08:15:42 +0000</pubDate>
		<dc:creator>Kash Farooq</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Programmatically searching]]></category>

		<guid isPermaLink="false">http://kashfarooq.wordpress.com/?p=546</guid>
		<description><![CDATA[Also see Programmatically searching Google (Part 2): Using the RESTful interface I needed to do some web searches and record the host names that I found, so I started investigating what APIs Google exposed. I found the &#8220;Google APIs for .NET Framework&#8221; hosted on Google Code. There hasn&#8217;t been much activity on this project recently &#8211; the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=546&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em>Also see <a title="Edit “Programatically searching Google (Part 2): Using the RESTful interface”" href="http://kashfarooq.wordpress.com/wp-admin/post.php?post=563&amp;action=edit">Programmatically searching Google (Part 2): Using the RESTful interface</a></em></p>
<p>I needed to do some web searches and record the host names that I found, so I started investigating what APIs Google exposed.</p>
<p>I found the &#8220;<a href="http://code.google.com/p/google-api-for-dotnet/">Google APIs for .NET Framework</a>&#8221; hosted on Google Code. There hasn&#8217;t been much activity on this project recently &#8211; the last release was April 2010 &#8211; and there is not much documentation, but it works and it is simple to use.</p>
<p>It provides two sets of libraries: one that wraps Google Search and one that wraps Google Translate.</p>
<p>Here is an example of a search:</p>
<p><pre class="brush: csharp;">
public void SearchForSomethingUsingLib() {
  var client = new GwebSearchClient(&quot;http://mywebsite.com&quot;);
  var results = client.Search(&quot;google api for .NET&quot;, 100);
  foreach (var webResult in results) {
   Console.WriteLine(&quot;{0}, {1}, {2}&quot;, webResult.Title, webResult.Url, webResult.Content);
  }
}
</pre></p>
<p>The &#8217;100&#8242; in the above example indicates the number of search results to return.</p>
<p>What puzzled me was that the set of results returned didn&#8217;t appear to have a concept of paging, and the library didn&#8217;t seem to have a &#8220;Search Paged&#8221; method. What if I had asked for 1000000 results? Surely the API wasn&#8217;t going to get 1000000 results in one go and load them all into a List?</p>
<p>I fired up reflector. The API definitely returned a straight forward generic list. No delayed execution &#8211; one Web Request sent to Google, followed by one &#8220;new List&lt;T&gt;&#8221; to return the results.</p>
<p>I needed to investigate further, and I&#8217;ll look at that in Part 2.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kashfarooq.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kashfarooq.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kashfarooq.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kashfarooq.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kashfarooq.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kashfarooq.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kashfarooq.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kashfarooq.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kashfarooq.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kashfarooq.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kashfarooq.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kashfarooq.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kashfarooq.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kashfarooq.wordpress.com/546/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kashfarooq.wordpress.com&amp;blog=5686516&amp;post=546&amp;subd=kashfarooq&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kashfarooq.wordpress.com/2011/01/24/programmatically-searching-google-part-1-the-google-api-for-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/05cbab55eb1f89a2d954b893f1b6bbb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Kash</media:title>
		</media:content>
	</item>
	</channel>
</rss>
