<?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/"
	>

<channel>
	<title>Ruchit Surati&#039;s blog &#187; Programming</title>
	<atom:link href="http://www.ruchitsurati.net/index.php/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ruchitsurati.net</link>
	<description>thoughts and ideas of a .net developer</description>
	<lastBuildDate>Wed, 23 Feb 2011 19:48:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Building ASP.Net Applications &#8211; Best practices</title>
		<link>http://www.ruchitsurati.net/index.php/2011/02/18/building-asp-net-best-practices/</link>
		<comments>http://www.ruchitsurati.net/index.php/2011/02/18/building-asp-net-best-practices/#comments</comments>
		<pubDate>Fri, 18 Feb 2011 12:05:05 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/?p=496</guid>
		<description><![CDATA[ASP.Net has come a long way and it is by far the most widely accepted development platform (no offense to php, you have your own place..). I have been using it since long and I just love it. This post is about my best practices while working on an ASP.Net project. Web applications are more [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">ASP.Net has come a long way and it is by far the most widely accepted development platform (no offense to php, you have your own place..). I have been using it since long and I just love it. This post is about my best practices while working on an ASP.Net project. Web applications are more performance conscious compared to a native windows client app. You need to take care of many aspects before you actually call it a performing production-grade web-application. Here, I have published a non-exhaustive set of my best practices.</p>
<p style="text-align: justify;"><strong>Create a common base page for all your asp.net pages.</strong> This page will derive from System.Web.UI.Page and you may put this under YourApp.Web.UI custom namespace. Let all your asp.net pages derive from YourApp.Web.UI.PageBase class. This can reduce a lot of pain when it comes to changing a common behavior or functional aspects across all pages in your application. Like exposing common properties and methods that are used across all the pages.</p>
<pre class="brush: csharp; title: ;">
public class PageBase : System.Web.UI.Page
{
    public PageBase()
    {
        this.Load += new EventHandler(PageBase_Load);
    }

    protected string LoggedInUserName {get;private set;}

    void PageBase_Load(object sender, EventArgs e)
    {
        //Set the LoggedInUserName here, that all pages can access.
    }
}
</pre>
<p style="text-align: justify;"><strong>Use Application_OnError handler to gracefully handle any orphan exceptions.</strong> In medium to large size projects, you will have many developers working on the same project, and as a team-lead or module-lead, you are not going to have the scope to check if all developers are dealing with exceptions meticulously. The uncaught orphan exceptions cause the <em><strong>Yellow Screen of death</strong></em>, crash your application and client will see all the things that he or she should not see. Use Application_OnError event within the global.asax where all those nasty unattended exceptions will land up. From here, you can log the exception and notify respective authorities about the error. This will also help you trace back to the piece of code that caused this. You can makr the exception as Handled and show a standard error page to the client telling him &#8211; &#8220;something went wrong, we will fix it soon. Click here to continue&#8221; or something like that that does not ruin the reputation of your application.</p>
<p style="text-align: justify;"><strong>Use MembershipProvider and RoleProvider. And Never use inbuilt ProfileProvider</strong> &#8211; Many developers are totally ignorant about the using the providers that shipped with ASP.Net 2.0. We use them heavily and it takes care of our entire user and roles management mechanism leaving us with more time to focus on the actual application. I recommend not to use the inbuilt ProfileProvider since I do not like the way they store the information (They store everything in plain strings.). This could slow down the performance of your application when you have large number of users. We have written our own custom MembershipProvider and RoleProvider and they just work great.</p>
<p style="text-align: justify;"><strong>Use Firebug for client-side debugging.</strong> In web development, the tools that you use for development also make a great difference. The rendered mark-up is loaded on the client-side browser where you need to inspect the elements in the DOM and its attributes. Firebug is a boon to web-developers. It knows what you need before you ask. Les you inspect an element with all details that you may ever want to know. Firebug also has YSlow extension which can evaluate the performance-rank of your web-page and advise you on how to improve it.</p>
<p><a href="http://getfirebug.com/whatisfirebug"><img class="size-medium wp-image-499 alignnone" title="firebug" src="http://www.ruchitsurati.net/wp-content/uploads/2011/02/firebug-300x144.png" alt="" width="300" height="144" /></a></p>
<p style="text-align: justify;"><strong>Use jQuery for client-scripting.</strong> jQuery is one of the most essential part of any web application, be it any platform. It has changed the way we script for clients. It has established a standard for client scripting. I have to make sure in any web application project that I work on, I must have at least one cool jQuery ninja programmer within the team. Try it and you will understand what you have been missing till date.</p>
<p><a href="http://www.ruchitsurati.net/wp-content/uploads/2011/02/jquery-logo1.png"><img class="alignnone size-full wp-image-533" title="jquery-logo" src="http://www.ruchitsurati.net/wp-content/uploads/2011/02/jquery-logo1.png" alt="" width="175" height="175" /></a></p>
<p style="text-align: justify;"><strong>Never store User Authentication information in session</strong> or do not use sessions to judge if user is logged on. Every asp.net request carries an HttpCookie for authentication and if you are using FormsAuthentication,you will find all authentication information within the Page object itself. Store only minimum necessary information in sessions.</p>
<p style="text-align: justify;"><strong>Disable ViewState where you dont need it.</strong> In a page if the UIobject does not need to retain the state across post-backs, just disable the viewstate for the object by setting <em>EnableViewState </em>property to false. At times you may want to disable the viewstate for an entire page. You will soon figure out the page loading faster consuming less bytes of data to transport.</p>
<p style="text-align: justify;"><strong>Never ever Deploy asp.net application under debug configuration on production. </strong>To me this is a crime. You can never ever deploy a build with debug symbols or config. This is valid for any sort of .Net project whose end-output is a .Net assembly. SottGu has written a <a href="http://weblogs.asp.net/scottgu/archive/2006/04/11/Don_1920_t-run-production-ASP.NET-Applications-with-debug_3D001D20_true_1D20_-enabled.aspx">nice post</a> on this as to why you should not do this.</p>
<p style="text-align: justify;"><strong>User Web Deployment projects.</strong> I love simple and compact things. Web Deployment project can compile and merge all your code-behind classes and the classes in app_code into one single project output assembly which you just need to put in the bin directory of deployment. It can transform web.config sections and replace with production server settings during post compilation phase. I have seen projects with 200 pages and their individual assemblies being deployed in bin which means you have a big assembly mess in the bin directory. How about summing them all up in single assembly ? <a href="http://msdn.microsoft.com/en-us/magazine/cc163448.aspx" target="_blank">Web deployment projects</a> is just worth for this single feature.</p>
<p style="text-align: justify;"><strong>Use Cookie-less domains to serve static resources</strong> like images, scripts, styles etc. Each client request brings along a whole bunch of cookies, that you do not need while serving pictures or scripts from server. So host those resources on a cookie-less domain. We have a sub-domain setup to serve cookie-less resources. So we host all our images and scripts on the sub-domain. and from the primary application we just point the resource by its url on the sub-domain. We make sure sub-domain remains cookie-free by not serving any dynamic script on that domain or by creating any asp.net or php sessions. If you dont write cookies from domain, the domain will be cookie-less.</p>
<p style="text-align: justify;"><strong>Minify scripts, stylesheets and HTML responses</strong> from the server. Markups and scripts are meant for browser engine and they never need to be in readable format post-production. Removing unnecessary line-breaks and white-spaces can improve the time-to-load and bandwidth optimization.</p>
<p style="text-align: justify;">These are the few important things, that I must do in any web application. I am sure you would have your own tricks of the trade that others can benefit from. Please feel free to throw in your ideas and techniques for writing well-performing asp.net applications, in comments to this post.</p>
<p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-3020293614675538";
/* 300x250, created 14-July-2010 */
google_ad_slot = "4146580937";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2011/02/18/building-asp-net-best-practices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>understanding ‘using’ block in C#</title>
		<link>http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%e2%80%98using%e2%80%99-block-in-c/</link>
		<comments>http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%e2%80%98using%e2%80%99-block-in-c/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 16:46:47 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[net-framework]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/?p=422</guid>
		<description><![CDATA[using block in C# comes very handly while dealing with disposable objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can&#8217;t predict when exactly the object will be garbage collected. Many times we need to make [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">using block in C# comes very handly while dealing with <em>disposable</em> objects. Disposable objects are those objects that can explicitly release the resources they use when called to dispose. As we know .Net garbage collection is non-deterministic so you can&#8217;t predict when exactly the object will be garbage collected. Many times we need to make sure the object is disposed along with all the resources it uses immediately after the purpose is served. This becomes possible with using block. <em>using </em>block in C# lets you deal with <em>disposable</em> objects effectively. But how does it work ? <strong>How does using block ensure the object is immediately disposed after the scope of the using block?</strong></p>
<p style="text-align: justify;">Lets look at what MSDN has to say. As per the msdn</p>
<blockquote style="text-align: justify;"><p><em>using</em> block Defines a scope, outside of which an object or objects will be disposed.</p></blockquote>
<p style="text-align: justify; clear: both;"><em>The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using  statement must implement the IDisposable  interface. This interface provides the Dispose  method, which should release the object&#8217;s resources.</em></p>
<p style="text-align: justify;">Surprisingly even MSDN does not clarify how does this happen under the hood. It only says the object has to implement <em>IDisposable </em>interface that provides <em>Dispose </em>method on the object implementing the interface.  So to dispose the object it will need to call the Dispose method on the object which will cleanup and release the resources used by the object.</p>
<p style="text-align: justify;">This led me to write some code and analyze the generated IL where I found the answers. Have a look at this code. I&#8217;ve written a class <em>Car </em>and made it <em>IDisposable </em>so that I can club its&#8217; lifetime with <em>using</em> block.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    public class Car : IDisposable
    {
        public Car(int id)
        {
            this.Id = id;
        }

        public int Id { get; set; }

        public void Run()
        {
            Console.WriteLine(&quot;Car {0} is running.&quot;, this.Id.ToString());
        }

        #region IDisposable Members

        public void Dispose()
        {
            Console.WriteLine(&quot;Releasing resources used by Car object : &quot; + this.Id.ToString());
        }

        #endregion
    }
}
</pre>
<p style="text-align: justify;">Here&#8217;s my client-code. A sample ConsoleApplication that uses the Car object within the using block.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Car myCar = new Car(1))
            {
                myCar.Run();
            }
        }
    }
}
</pre>
<p style="text-align: justify;">The output was obvious. Immediately after the using block the Dispose method of the Car object is called. Note that there are no signs of Dispose() method being called explicitly, still the method is called. Lets look at the generated IL.</p>
<pre class="brush: csharp; title: ;">
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       37 (0x25)
  .maxstack  2
  .locals init ([0] class BlogSamples.Car myCar,
           [1] bool CS$4$0000)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  newobj     instance void BlogSamples.Car::.ctor(int32)
  IL_0007:  stloc.0
  .try
  {
    IL_0008:  nop
    IL_0009:  ldloc.0
    IL_000a:  callvirt   instance void BlogSamples.Car::Run()
    IL_000f:  nop
    IL_0010:  nop
    IL_0011:  leave.s    IL_0023
  }  // end .try
  finally
  {
    IL_0013:  ldloc.0
    IL_0014:  ldnull
    IL_0015:  ceq
    IL_0017:  stloc.1
    IL_0018:  ldloc.1
    IL_0019:  brtrue.s   IL_0022
    IL_001b:  ldloc.0
    IL_001c:  callvirt   instance void [mscorlib]System.IDisposable::Dispose()
    IL_0021:  nop
    IL_0022:  endfinally
  }  // end handler
  IL_0023:  nop
  IL_0024:  ret
} // end of method Program::Main
</pre>
<p style="text-align: justify;">Do you spot that compiler has introduced <em>try/finally</em> block and replaced it with <em>using </em>block. But why did compiler do that ? Lets observe the code and attempt to write similar C# code for better understanding. After careful analysis and reverse-engineering the equivalent C# code would look something as following.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare myCar object with FullName of the type as seen in IL.
            BlogSamples.Car myCar;

            //Instantiate the object by calling the constructor, matching the flow of IL.
            myCar = new Car(1);

            try
            {
                myCar.Run();
            }
            finally
            {
                if(myCar != null)
                    myCar.Dispose();
            }
        }
    }
}
</pre>
<p style="text-align: justify;">Above code is very clear. All it does is replace the code within the using block into the try block and calls the Dispose() method of the object in the finally block. As we all know, the code written in finally block gets executed in any situation even in case of any handled or un-handled exception. And this is how the using block ensures that the objects used with the using block are disposed for sure.</p>
<blockquote><p>In fact using block is just a syntactic sugar for this pattern of code.</p></blockquote>
<p style="text-align: justify; clear: both;">
<p>Some of you might wonder, how does the generated IL of the new reverse-engineered code look like. The IL of the reverse-engineered looks like this.</p>
<pre class="brush: csharp; title: ;">
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       31 (0x1f)
  .maxstack  2
  .locals init ([0] class BlogSamples.Car myCar)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  newobj     instance void BlogSamples.Car::.ctor(int32)
  IL_0007:  stloc.0
  .try
  {
    IL_0008:  nop
    IL_0009:  ldloc.0
    IL_000a:  callvirt   instance void BlogSamples.Car::Run()
    IL_000f:  nop
    IL_0010:  nop
    IL_0011:  leave.s    IL_001d
  }  // end .try
  finally
  {
    IL_0013:  nop
    IL_0014:  ldloc.0
    IL_0015:  callvirt   instance void BlogSamples.Car::Dispose()
    IL_001a:  nop
    IL_001b:  nop
    IL_001c:  endfinally
  }  // end handler
  IL_001d:  nop
  IL_001e:  ret
} // end of method Program::Main
</pre>
<blockquote><p>Needless to mention that the IL in both the cases is identical to each other which proves the point that the using block is nothing but a syntactic sugar.</p></blockquote>
<p style="text-align: justify; clear: both;"><strong>You might ask what if the constructor throws an exception.</strong> In this case the control would not move forward and never enter the proceeding try block. The object myCar still remains null. However you can wrap the using block in a try/catch block as shown below and handle the situation gracefully.</p>
<pre class="brush: csharp; title: ;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BlogSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (Car myCar = new Car(1))
                {
                    myCar.Run();
                }
            }
            catch
            {
                //Handle the situation gracefully.
            }
        }
    }
}
</pre>
<blockquote><p>But why C# designers did not wrap object construction within the try block.</p></blockquote>
<p style="text-align: justify; clear: both;">
The reason is simple. If you wrap both declaration and instantiation within the try block then <strong>the object would be out of scope for the proceeding finally block</strong> and the code will not compile at because, for finally block the object hardly exists. If you only wrap the construction in the try block and keep declaration before the try block, even in that case the it will not compile since it finds <strong>use of an unassigned variable which is not allowed in C#</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2010/07/28/understanding-%e2%80%98using%e2%80%99-block-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Decorator Pattern with C#</title>
		<link>http://www.ruchitsurati.net/index.php/2010/07/23/decorator-pattern-with-c/</link>
		<comments>http://www.ruchitsurati.net/index.php/2010/07/23/decorator-pattern-with-c/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 17:34:47 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[design-patterns]]></category>
		<category><![CDATA[ooad]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/?p=431</guid>
		<description><![CDATA[Decorator pattern achieves a single objective of dynamically adding responsibilities to any object. Consider a case of a pizza shop. In the pizza shop they will sale a few pizza varieties and have toppings that customers can order additionally on top of a pizza. Customer can order a pizza and add as many as toppings [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p><strong>Decorator pattern achieves a single objective of dynamically adding  responsibilities to any object.</strong></p></blockquote>
<p style="text-align: justify;">Consider a case of a pizza shop. In the pizza shop they will sale a few pizza varieties and have toppings that customers can order additionally on top of a pizza. Customer can order a pizza and add as many as toppings on the pizza. The cost of the ordered pizza will have to be calculated with pizza and all additional toppings. Now imagine a situation wherein if the pizza shop has to provide prices for each combination of pizza and topping. Even if there are four basic pizzas and 8 different toppings, the application would go crazy maintaining all concrete combination of pizzas and toppings. It is impractical to keep all combination in the menu. You&#8217;ll do enough to lose the customer when you expect him to go through such a long menu and do humongous brain-job.</p>
<p style="text-align: justify;">Here comes the decorator pattern.</p>
<p style="text-align: justify;">As per the decorator pattern, you will implement toppings as decorators and pizzas will be decorated by those toppings&#8217; decorators. Practically each customer would want toppings of his desire and final bill-amount will be composed of the base pizzas and additionally ordered toppings. Each topping decorator would know about the pizzas that it is decorating and it&#8217;s price. </p>
<p style="text-align: justify;">Here&#8217;s a code-example of explanation above.</p>
<pre class="brush: csharp; title: ;">

//All your pizzas will inherit from this BasePizza class to identify themselves as pizzas.
public abstract class BasePizza
{
    protected double myPrice;

    //This method will return the price of the pizza object.
    public virtual double GetPrice()
    {
        return this.myPrice;
    }
}

//All toppings will inherit from this ToppingsDecorator class to be able to be added to any pizza in the pizza-shop.
public abstract class ToppingsDecorator : BasePizza
{
    //Each topping will need to know to which pizza it is being added to.
    protected BasePizza pizza;
    public ToppingsDecorator(BasePizza pizzaToDecorate)
    {
        this.pizza = pizzaToDecorate;
    }

    //This method will return cumulative price of both pizza and the topping.
    public override double GetPrice()
    {
        return (this.pizza.GetPrice() + this.myPrice);
    }
}

class Program
{
    [STAThread]
    static void Main()
    {
        //Client-code

        //First - order your base pizza. We'll add toppings onto this pizza.
        Margherita pizza = new Margherita();
        Console.WriteLine(&quot;Plain Margherita: &quot; + pizza.GetPrice().ToString());

        //Add extra cheese.
        ExtraCheeseTopping moreCheese = new ExtraCheeseTopping(pizza);

        //Add some more cheese and make it double extra cheese.
        ExtraCheeseTopping someMoreCheese = new ExtraCheeseTopping(moreCheese);
        Console.WriteLine(&quot;Plain Margherita with double extra cheese: &quot; + someMoreCheese.GetPrice().ToString());

        //Like mushrroms ? Add that too.
        MushroomTopping moreMushroom = new MushroomTopping(someMoreCheese);
        Console.WriteLine(&quot;Plain Margherita with double extra cheese with mushroom: &quot; + moreMushroom.GetPrice().ToString());

        //Throw in some Jalapeno and make it sour and spicy.
        JalapenoToping moreJalapeno = new JalapenoToping(moreMushroom);

        //Add here's your final pizza.
        Console.WriteLine(&quot;Plain Margherita with double extra cheese with mushroom with Jalapeno: &quot; + moreJalapeno.GetPrice().ToString());

    }
}

public class Margherita : BasePizza
{
    public Margherita()
    {
        this.myPrice = 6.99;
    }
}

public class Gourmet : BasePizza
{
    public Gourmet()
    {
        this.myPrice = 7.49;
    }
}

public class ExtraCheeseTopping : ToppingsDecorator
{
    public ExtraCheeseTopping(BasePizza pizzaToDecorate)
        : base(pizzaToDecorate)
    {
        this.myPrice = 0.99;
    }
}

public class MushroomTopping : ToppingsDecorator
{
    public MushroomTopping(BasePizza pizzaToDecorate)
        : base(pizzaToDecorate)
    {
        this.myPrice = 1.49;
    }
}

public class JalapenoToping : ToppingsDecorator
{
    public JalapenoToping(BasePizza pizzaToDecorate)
        : base(pizzaToDecorate)
    {
        this.myPrice = 1.49;
    }
}
</pre>
<p>
Note that, <strong>GetPrice()</strong> method of Topping object would return cumulative price of both pizza and the topping.
</p>
<p><img src="http://ruchitsurati.net/myfiles/decorator.png" alt="alt text" /></p>
<p>
<script type="text/javascript"><!--
google_ad_client = "pub-3020293614675538";
/* 300x250, created 14-July-2010 */
google_ad_slot = "4146580937";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2010/07/23/decorator-pattern-with-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Sealed classes as Generic type-constraints</title>
		<link>http://www.ruchitsurati.net/index.php/2010/07/07/sealed-classes-as-generic-constraints/</link>
		<comments>http://www.ruchitsurati.net/index.php/2010/07/07/sealed-classes-as-generic-constraints/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 14:23:08 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/?p=348</guid>
		<description><![CDATA[We make heavy use of generics in our projects. Generics are really great deal when it comes to run-time polymorphism. Recently, one of my colleague came up with an idea to use a sealed class as generic type constraint. He wrote a sample code that looks like this. public sealed class MySealedClass { public MySealedClass() [...]]]></description>
			<content:encoded><![CDATA[<p>We make heavy use of generics in our projects. Generics are really great deal when it comes to run-time polymorphism. Recently, one of my colleague came up with an idea to use a sealed class as generic type constraint. He wrote a sample code that looks like this.</p>
<pre class="brush: csharp; highlight: [1,7]; title: ;">
public sealed class MySealedClass
{
    public MySealedClass() { }
}

public class MyGeneric&lt;T&gt;
        where T : MySealedClass
{
    public MyGeneric() { }
}
</pre>
<p style="text-align: justify;">Surprisingly, Above code gives following compile error.</p>
<p class="message notice" style="text-align: justify;">&#8216;MySealedClass&#8217; is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.</p>
<p style="text-align: justify;">That was strange. We never observed such behavior before. Code was absolutely correct and it seemed like language designers had intentionally put this constraint to not allow sealed classed as generic constraints. But what must be the reason behind this ? Finally we had our thoughts in place and found the fact why it is so.</p>
<p style="text-align: justify;">To understand, why sealed classes are not allowed to be generic type constraints, let us assume that sealed classes are allowed to be type constraints to generics. With this assumption the code above is valid and compiles successfully. Now lets write some client-code that would use this generic.</p>
<pre class="brush: csharp; title: ;">
//create and instantiate an object of type MyGeneric
MyGeneric&lt;MySealedClass&gt; objGeneric = new MyGeneric&lt;MySealedClass&gt;();
</pre>
<p style="text-align: justify;">Fair enough, this looks ok.</p>
<p style="text-align: justify;">Now lets check what other types we can pass to MyGeneric type-argument at runtime. By defination, it has to be MySealedClass itself or any type that inherits from MySealedClass.</p>
<p style="text-align: justify;">But won&#8217;t MySealedClass be the only valid type-argument for MyGeneric since MySealedClass cannot be inherited further and there will be no class that inherits from MySealedClass ? Doesn&#8217;t this defeat the whole idea of putting MySealedClass in type constraint to MyGeneric, since there&#8217;ll be no other valid-type argument except MySealedClass itself ? If MySealedClass is going to be the only valid type for MyGeneric, then  there&#8217;s no point in  defining MyGeneric as generic at all. Can&#8217;t we simply code against the type MySealedClass ?</p>
<p style="text-align: justify;">We could finally realize the reason why language designers of  C# didn&#8217;t allow sealed classes as generic type-argument. quite enlightening.</p>
<p style="text-align: justify;">While doing this we also came to realize why static classes are also not allowed to be generic type-constraints, though it&#8217;s very much obvious that static classes can never ever be generic type constraints. We found our answer in the compiled IL, where the <strong>static classes are marked as both abstract and sealed. Abstract since they cannot be instantiated and sealed since they cannot be inherited, hence cannot be generic type-constraints. </strong>In general only those types can be generic type-constraints which can have inheritance hierarchy below them, this includes interfaces, any non-sealed abstract or concrete classes.</p>
<p>
<script type="text/javascript"><!--
google_ad_client = "pub-3020293614675538";
/* 300x250, created 14-July-2010 */
google_ad_slot = "4146580937";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2010/07/07/sealed-classes-as-generic-constraints/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Mobile Web Server &#8211; An Apache port to Symbian Platform</title>
		<link>http://www.ruchitsurati.net/index.php/2008/01/29/mobile-web-server-an-apache-port-to-symbian-platform/</link>
		<comments>http://www.ruchitsurati.net/index.php/2008/01/29/mobile-web-server-an-apache-port-to-symbian-platform/#comments</comments>
		<pubDate>Tue, 29 Jan 2008 05:52:25 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[mobile-application]]></category>
		<category><![CDATA[symbian]]></category>
		<category><![CDATA[web-server]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/post.aspx?id=2fd0998a-19b0-4c0b-b80c-c22f8b189155</guid>
		<description><![CDATA[Yes, you&#8217;ve got it right. The first ever HTTP web server for mobiles and it does all you can expect, in fact it does more then what you expect. Nokia Beta Labs has come up with a Web Server for Mobile phones. The first working prototype was deployed in October, 2007 and I&#8217;ve been chasing [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, you&#8217;ve got it right. The first ever HTTP web server for mobiles and it does all you can expect, in fact it does more then what you expect. Nokia Beta Labs has come up with a Web Server for Mobile phones. The first working prototype was deployed in October, 2007 and I&#8217;ve been chasing the project for every bit of it so far. Currently you have the version 1.2 Beta released on their <a title="Mobile Web Server - Official Web-site" href="http://mymobilesite.net/" target="_blank">web-site</a>. Basically, it&#8217;s an Apache port to Symbian platform and the web-server is deployed as a Symbian application which comes as a SIS file package.</p>
<p>I will blog about this as a series of posts, with this being the Part I itself. In this post, I will have you installed your first working mobile web server and provide you with features and functions. Later parts will include the architecture, how it works, the application areas and will try to elaborate more useful information and details on the web-server. So, here we go..</p>
<h3>Getting Started:</h3>
<p>To start with it, you must register and you can do so by filling up the form at this <a title="Mobile Web Server Registration" href="https://secure.mymobilesite.net/register/" target="_blank">location</a>. You must choose a valid and available Sub-Domain name for making your cell-phone uniquely reachable on the internet. Like mine is <strong>ruchit</strong>.mymobilesite.net and you can hit to the web-server running on my cell-phone by typing this URL in any web-browser, anywhere in the world. So, please choose a good name as well. The web-server can host CGI applications on py60 (Python for S60), static HTML web-pages and it comes with pre-bundled application with basic services which you can access at your URL, which in my case is <a href="http://ruchit.mymobilesite.net">http://ruchit.mymobilesite.net</a> , as I said earlier. Once you&#8217;ve reserved a unique location on the web for your Cell-Phone + Web-Server, you can download the web-server and install it on your cell-phone. You can download the server from <a title="Mobile Web Server - Download" href="http://mymobilesite.net/download/" target="_blank">here</a>. You can use Nokia PC suite to install the server application. After installation, your application menu should display with the icon of the server like this..</p>
<p><a href="http://www.ruchitsurati.net/myfiles/mobile-web-server.jpg"><img style="border: 0px;" src="http://www.ruchitsurati.net/myfiles/mobile-web-server.jpg" border="0" alt="webservericon" /></a></p>
<p>Now, start the application by clicking on the icon and you should see the main application menu. Now, our objective is to let the server know is identity by binding it to the respective URL, in my case as you know it&#8217;d be <a href="http://ruchit.mymobilesite.net">http://ruchit.mymobilesite.net</a>. When you run it for the first time, it will detect it as fresh installation and will prompt you to punch in the most basic details to let itself bind it to a unique Internet location. You can download the <a title="Mobile Web Server - User Guide" href="http://mymobilesite.net/files/MobileWebServer_UG_en_v12.pdf" target="_blank">User Manual</a> from the web-site in order to complete the installation and play around with it in more details. Once you&#8217;ve started the server successfully you should see this screen on your mobile.</p>
<p><a href="http://www.ruchitsurati.net/myfiles/mobile-web-server-2.jpg"><img style="border: 0px;" src="http://www.ruchitsurati.net/myfiles/mobile-web-server-2.jpg" border="0" alt="webserver1" /></a></p>
<p>And yes, Symbian S60 2nd and 3rd edition phones have multitasking capabilities, so you can let this server be running in background continue working as normal. Phone like N95 and higher E series phones, have floating point units, which makes it a breeze.</p>
<h3>Features and Functions:</h3>
<p>You/Anybody can access your Web-Server by typing the associated unique URL, you gained as part of your registration process. You can have administrator logging into your cell-phone or you can entertain guest users as well. They will have following features accessible.</p>
<p><strong>Camera:</strong> The person logged in can access your camera. The person can take pictures by clicking a single button and he can watch it straight on the browser and he can save that picture on local desktop. He can&#8217;t have the video streaming as this way beyond the scope of possibilities, demanding good amount of resources. Yes, you can think of real good ideas to tap on this feature. Like, you can so immediate sharing or remote cam kind of solution.</p>
<p><strong>Web Chat:</strong> You can chat with the cell-phone owner in real time with his approval. It supports some smileys  too.</p>
<p><strong>Messaging:</strong> You can send a single message to the cell-phone owner like a quick-drop message for owner&#8217;s information or for any other important stuff.</p>
<p><strong>Calendar:</strong> You can access person&#8217;s calendar entries right in the browser. You can manipulate them if you&#8217;ve enough rights or you can add one. How about adding your birth-day in your friends mobile without his knowledge and check back his expressions, thinking when reminded, &#8220;Hey, I never did it!&#8221;</p>
<p><strong>Phone Log:</strong> You can access owner&#8217;s Dialed Calls&#8217; Logs, Received Calls&#8217; Logs and Missed Calls&#8217; Logs in real time.</p>
<p><strong>Presence:</strong> You can view cell-phone&#8217;s status and availability information, on which the web-server is running. You can learn, if an active call is ongoing or what&#8217;s battery level of the server phone or even the data bearer of the web-server, either EDGE, 3G or WLAN.</p>
<p><strong>Send SMS:</strong> You can send an SMS to any-other cell-phone number from the web. This will be charged into owner&#8217;s telco. account.</p>
<p><strong>GuestBook:</strong> You can fill up the guest book of the owner, if you like.</p>
<p><strong>Contacts:</strong> You can access owner&#8217;s phone book on the web and manipulate, If you&#8217;ve got enough rights. How about checking a number you need without bothering your friend by asking, &#8220;Hey, do you have this guy&#8217;s number?&#8221;.</p>
<p><strong>Gallery:</strong> You will have access to owner&#8217;s pictures album both on phone memory and external memory facilities.</p>
<p>Well, there are more other exciting features like blogging, contact me and etc. You can check out and download the latest version at <a href="http://www.mymobilesite.net">http://www.mymobilesite.net</a>. Feel free to comment or write to me on my email <a href="mailto:ruchit@ruchitsurati.net">ruchit@ruchitsurati.net</a>. Please mark the subject as &#8216;<strong>Mobile Web Server</strong>&#8216;. More information on Mobile Web Server will follow this post in later posts. Till then Cheers!</p>
<p>Get Ready for the next generation of connected applications. It&#8217;s not that shallow as it seems. There&#8217;s lot more to it.</p>
<p>- Ruchit S.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2008/01/29/mobile-web-server-an-apache-port-to-symbian-platform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Year 2038 Bug &#8211; Y2K38 Problem &#8211; Many of your applications will crash</title>
		<link>http://www.ruchitsurati.net/index.php/2007/08/19/the-year-2038-bug-y2k38-problem-many-of-your-applications-will-crash/</link>
		<comments>http://www.ruchitsurati.net/index.php/2007/08/19/the-year-2038-bug-y2k38-problem-many-of-your-applications-will-crash/#comments</comments>
		<pubDate>Sun, 19 Aug 2007 23:12:00 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[y2k38]]></category>
		<category><![CDATA[year-2038-bug]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/post.aspx?id=41e98c59-7100-4158-a40d-44f5925db100</guid>
		<description><![CDATA[Try this First. Sign out from yahoo messenger or gmail talk. Open your System Date and Time Settings. Change the year to anything beyond 2038. You can try setting the year to 2040. Now try logging in to either of the messenger. It does not log in and gives you some error. Surprised! So, Where&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<h2>Try this First.<br /></h2>
<blockquote><p>Sign out from yahoo messenger or gmail talk. Open your System Date and Time Settings. Change the year to anything beyond 2038. You can try setting the year to 2040. Now try logging in to either of the messenger. It does not log in and gives you some error. Surprised! </p>
</blockquote>
<h2>So, Where&#8217;s the problem ?</h2>
<p>The source of the problem is actually the way some(major) applications store their date/time data types. Programmes using POSIX time representation will be affected by this problem. The structure time_t is a value type which stores time in a 32-bit signed integer. It stores the time as number of seconds elapsed since <strong>January 1, 1970</strong>. So it is capable of representing time which can be addressed within total of <strong><em>2<sup>31</sup></em></strong> seconds. According to this, the latest time that it can store is <strong>03:14:07 UTC, Tuesday, January 19, 2038</strong>. After this time, the sign bit of the 32-bit signed integer will be set and it will represent a negative number. As I said, the time is stored as number of seconds elapsed since 1st January 1970, this negative number will be added to compute the time as per the POSIX standards. But this being a negative number it will calculate the time by subtracting this many seconds from 1st January 1970 which will eventually generate a historical date-time which will cause the applications to fail. This time will be Friday, December 1901 and is called the wrap-around date. Applications written in C in many operating system will also be affected as the POSIX presentation of time is widely used there. The animation below visualizes actual scenario in an easier manner. This bug is often denoted as &#8220;Y2038&#8243;, &#8220;Y2K38&#8243;, or &#8220;Y2.038K&#8221; bug. </p>
<p align="center"><img height="130" src="image.axd?picture=Year_2038_problem.gif" width="400"></p>
<h2>Simulate the bug in a C Programme.</h2>
<p>The following ANSI C programme when compiled simulates the bug. The output produced by the programme is also attached below the code. This code has been been referred from <a href="http://www.2038bug.com/demo.html" target="_blank">here</a>. </p>
<pre>#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;unistd.h&gt;
#include &lt;time.h&gt;
int main (int argc, char **argv)
{
       time_t t;
       t = (time_t) 1000000000;
       printf ("%d, %s", (int) t, asctime (gmtime (&amp;t)));
       t = (time_t) (0x7FFFFFFF);
       printf ("%d, %s", (int) t, asctime (gmtime (&amp;t)));
       t++;
       printf ("%d, %s", (int) t, asctime (gmtime (&amp;t)));

return 0;
} </pre>
<h4>Output : </h4>
<pre>1000000000, Sun Sep 9 01:46:40 20012147483647,
Tue Jan 19 03:14:07 2038-2147483648,
Fri Dec 13 20:45:52 1901</pre>
<p>Above programme being a strict ANSI, should compile using any C compiler on any platform. Now lets take a look at a perl script on both UNIX and Windows 2000. This script has been referred from <a href="http://maul.deepsky.com/~merovech/2038.html" target="_blank">here</a>.</p>
<pre>#!/usr/bin/perl #
# I've seen a few versions of this algorithm
# online, I don't know who to credit. I assume
# this code to by GPL unless proven otherwise.
# Comments provided by William Porquet, February 2004.
# You may need to change the line above to # reflect the location of your Perl binary
# (e.g. "#!/usr/local/bin/perl").
# Also change this file's name to '2038.pl'.
# Don't forget to make this file +x with "chmod".
# On Linux, you can run this from a command line like this:
# ./2038.pl use POSIX;
# Use POSIX (Portable Operating System Interface),
# a set of standard operating system interfaces.

$ENV{'TZ'} = "GMT";

# Set the Time Zone to GMT (Greenwich Mean Time) for date
# calculations.

for ($clock = 2147483641; $clock &lt; 2147483651; $clock++) {
       print ctime($clock); }

# Count up in seconds of Epoch time just before and after the
# critical event.
# Print out the corresponding date in Gregorian calendar
# for each result.
# Are the date and time outputs correct after the critical
# event second?
        </pre>
<p>A mere handful of operating systems appear to be unaffected by the year 2038 bug so far. For example, the output of this script on Debian GNU/Linux (kernel 2.4.22): </p>
<p># ./2038.pl<br />Tue Jan 19 03:14:01 2038<br />Tue Jan 19 03:14:02 2038<br />Tue Jan 19 03:14:03 2038<br />Tue Jan 19 03:14:04 2038<br />Tue Jan 19 03:14:05 2038<br />Tue Jan 19 03:14:06 2038<br />Tue Jan 19 03:14:07 2038<br />Fri Dec 13 20:45:52 1901<br />Fri Dec 13 20:45:52 1901<br />Fri Dec 13 20:45:52 1901 </p>
<p>Windows 2000 Professional with ActivePerl 5.8.3.809 fails in such a manner that it stops displaying the date after the critical second : </p>
<p>C:\&gt;perl 2038.pl<br />Mon Jan 18 22:14:01 2038<br />Mon Jan 18 22:14:02 2038<br />Mon Jan 18 22:14:03 2038<br />Mon Jan 18 22:14:04 2038<br />Mon Jan 18 22:14:05 2038<br />Mon Jan 18 22:14:06 2038<br />Mon Jan 18 22:14:07 2038</p>
<h2>Do we have a solution ?</h2>
<p align="justify">Yes, Of course, There have been many solutions proposed worldwide for this problem. Few of them are listed here.</p>
<h4>1.) Re-define the time_t structure as 64-bit.</h4>
<p>This is not a solution as the binary compatibility of the software would break here. Programmes depending on the binary representations of time would be in trouble. So we can not even think of this one. </p>
<h4>2.) Change time_t from 32-bit signed to 32-bit unsigned.</h4>
<p>This seems to be good at first look, but this would just delay(post-pone) the judgement day to the year 2106 as it will give some more scope by adding another usable bit. You will be in the same trouble by then. So this is a feasible solution but not a practical one. </p>
<h4>3.) Shift from 32-bit systems to 64-bit systems.</h4>
<p>Most 64-bit architectures use 64 bit storage to represent time_t. The new wrap-around date with this new (signed)64 bit representation will not come before 290 billion years. It is positively predicted that by the year 2038 all 32-bit systems will be phased out and all systems will be 64-bit. </p>
<p>Thanks.</p>
<p>Ruchit S.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2007/08/19/the-year-2038-bug-y2k38-problem-many-of-your-applications-will-crash/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Tristate Theory &#8211; A whole new Number System</title>
		<link>http://www.ruchitsurati.net/index.php/2007/08/03/the-tristate-theory-a-whole-new-number-system/</link>
		<comments>http://www.ruchitsurati.net/index.php/2007/08/03/the-tristate-theory-a-whole-new-number-system/#comments</comments>
		<pubDate>Fri, 03 Aug 2007 11:33:00 +0000</pubDate>
		<dc:creator>Ruchit</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[computer-science]]></category>
		<category><![CDATA[number-system]]></category>
		<category><![CDATA[tristate]]></category>

		<guid isPermaLink="false">http://www.ruchitsurati.net/post.aspx?id=e2acdf9c-8210-4f97-818d-1210cd886aa2</guid>
		<description><![CDATA[Few months back I came across this wonderful work of someone called Abhijit Bhattacharjee. I&#39;m posting his work for readers. I&#39;m sure you&#39;ll like it as much as I did. Permission of the original author has been acquired for publishing his work on this blog. The post content are published with no changes except some [...]]]></description>
			<content:encoded><![CDATA[<p><!-- google_ad_section_start(weight=ignore) --></p>
<p>
<br />
<font size="4">F</font>ew months back I came across this wonderful work of someone called <a href="http://abhijit.info/" target="_blank"><em>Abhijit Bhattacharjee</em></a>. I&#39;m posting his work for readers. I&#39;m sure you&#39;ll like it as much as I did. Permission of the original author has been acquired for publishing his work on this blog. The post content are published with no changes except some cosmetics.
</p>
<p align="justify">
<em>&lt;&#8212;&#8212;&#8212; Orginal Work of Author Begins From Here &#8212;&#8212;&#8212;&gt;</em>
</p>
<h1 align="justify">The Tristate theory</h1>
<p align="justify">
<em>(All Rights Reserved Abhijit Bhattacharjee) </em>
</p>
<p align="justify">
It all started, a long time ago, when a roommate of mine at the academy gave me an innocuous puzzle to solve. He said &quot; If you were to have just four standard weights and you had to weigh all whole number weights between 1 and 40 kgs, on a physical balance, what would be your choice of the four standard weights ?&quot; While solving the problem and variations of it, I was coming across a lot of physical applications of such a situation. In fact the solution itself was very interesting and promising. The solution to the above puzzle was 1, 3, 9 and 27. Take another look. They are 3^0, 3^1, 3^2, 3^3. Three raised to the power of zero, one, two and three. I extended the problem for higher values and the symmetry still continued. The fact that all numbers however great could be expressed as a unique combination of sums and subtracts of radicals of three, each used only once, and in such a structured and predictable manner, offered great possibilities to me and it was not easy to sleep with it for all these years. Any number could be represented. Just think of any. Even negative numbers ! And later expanded to even include the fractional numbers ( See below ). The reason why this would be so, is not quite intuitive to understand, but can be illustrated with a &quot;swinging scaffolding diagram&quot;. And it has mind boggling applications that can radically change the way we do things. But before you go skeptical and leave, I am coming straightaway to something concrete to keep your faith. Given below is a programme written by me in Turbo Pascal to break any numbers into its components in the tristate manner.
</p>
<p align="justify">
<a href="http://abhijit.info/tristate/tristate.zip" target="_blank" title="Download Software (179KB) Tristate.zip">Download Software (179KB) Tristate.zip</a></p>
<p><font face="courier new,courier">program tristate;<br />
var n,a,b:real;task:boolean;choice:char;</p>
<p>procedure alpha;<br />
begin<br />
write(&#39; + &#39;,round(exp((a-1)*ln(3))));<br />
n:=round(n-(exp((a-1)*ln(3))));<br />
end;</p>
<p>procedure beta;<br />
begin<br />
write(&#39; + &#39;,round(exp(a*ln(3))));<br />
n:=round(n-exp(a*ln(3)));<br />
end;<br />
procedure gamma;<br />
begin<br />
write(&#39; &#8211; &#39;,round(exp((a-1)*ln(3))));<br />
n:=round(n-(exp((a-1)*ln(3))));<br />
end;<br />
procedure delta;<br />
begin<br />
write(&#39; &#8211; &#39;,round(exp(a*ln(3))));<br />
n:=round((n-exp(a*ln(3))));<br />
end;<br />
procedure positive;label 10;<br />
begin<br />
&nbsp; a:=0;<br />
&nbsp; repeat<br />
&nbsp; begin<br />
&nbsp;&nbsp;&nbsp; if n=round(exp(a*ln(3))) then<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; begin<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; write(&#39; + &#39;,round(exp(a*ln(3))));<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; task:=true;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto 10;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end;<br />
&nbsp;&nbsp;&nbsp; a:=a+1;<br />
&nbsp; end;<br />
until N&lt;round((exp(a*ln(3))));<br />
b:=round(exp(a*ln(3))-n);<br />
if b&gt;round(((exp(A*ln(3)))-1)/2) then alpha<br />
&nbsp;&nbsp; else<br />
&nbsp;&nbsp; if b&lt;=round(((exp((a)*ln(3)))-1)/2) then beta;<br />
10:;<br />
end;<br />
procedure negative;label 10;<br />
begin<br />
n:=-n;a:=0;<br />
repeat<br />
if n=round(exp(a*ln(3))) then<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; begin<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; write(&#39; &#8211; &#39;,round(exp(a*ln(3))));<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; task:=true;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; goto 10;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end;<br />
a:=a+1;<br />
until N&lt;round((exp(a*ln(3))));<br />
b:=round(exp(a*ln(3))-n);<br />
if b&gt;round(((exp((a)*ln(3)))-1)/2) then gamma<br />
else<br />
if b&lt;=round(((exp((a)*ln(3)))-1)/2) then delta;<br />
n:=-n;<br />
10:;<br />
end;<br />
procedure process;<br />
begin<br />
if n&lt;0 then negative<br />
else<br />
if n=0 then begin<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; write(&#39; 0&#39;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Task:=true;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end<br />
&nbsp;&nbsp;&nbsp;&nbsp; else<br />
if n&gt;0 then positive;<br />
end;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {MAIN PROGRAMME}<br />
begin<br />
choice:=&#39;y&#39;;<br />
writeln;writeln;<br />
repeat<br />
&nbsp; begin<br />
&nbsp; a:=0;n:=0;b:=0;<br />
&nbsp; task:=false;<br />
&nbsp; writeln;writeln;<br />
&nbsp; writeln(&#39; Enter your number (negative also allowed)&#39;);<br />
&nbsp; readln(n);<br />
&nbsp; writeln;<br />
&nbsp; write(round(n),&#39; = &#39;);<br />
&nbsp; while task=false do<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; begin<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; process;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; end;<br />
&nbsp; writeln;writeln;writeln;<br />
&nbsp; writeln(&#39;q to quit, c to continue crunching&#39;);<br />
&nbsp; readln(choice);<br />
&nbsp; end;<br />
until choice=&#39;q&#39;;<br />
writeln;writeln(&#39; Copyright Abhijit Bhattacharjee 20 Sept 1996&#39;);<br />
writeln(&#39; 5C Nilanjana Apts, 43 DH Road, Calcutta 34 ,INDIA&#39;);<br />
readln;<br />
end.<br />
</font><br />
Just compile the programme in a Turbo Pascal compiler. Naturally, the largest number crunched by this will be limited by the variable size definable in the compiler. But the algorithm remains same for the largest numbers conceivable. The programme shows us that practically all numbers positive or negative, however great or small can be expressed as a combination of sums and subtracts of radicals of three, each radical used just once. So this gives us another way of representing numbers. A brand new number system.</p>
<p>Lets see.<br />
3^0 = 1<br />
3^1 = 3<br />
3^2 = 9<br />
3^3 = 27<br />
3^4 = 81<br />
3^5 = 243<br />
3^6 = 729<br />
3^7 = 2187<br />
3^8 = 6561<br />
3^9 = 19683<br />
3^10 = 59049<br />
3^11 = 177147<br />
3^12 = 531441<br />
3^13 = 1594323<br />
3^14 = 4782963<br />
3^16 = 14348907<br />
3^17 = 43046721<br />
3^18 = 129140163<br />
3^19 = 387420489<br />
3^20 = 1162261467<br />
3^21 = 3486784401<br />
3^22 = 10460353203<br />
3^23 = 31381059609<br />
3^24 = 94143178827<br />
3^25 = 282429536481</p>
<p>Now watch some random numbers !<br />
57 = 81-27+3<br />
9586 = 6561+2187+729+81+27+1<br />
63779 = 59049+6561-2187+243+81+27+9-3-1<br />
7890459 = 14348907-4782969-1594323-59049-19683-2187-243+9-3<br />
57568678 = 43046721+14348907+177147-6561+2187+243+27+9-3+1</p>
<p>Do you need any more examples ? You can use the programme above. Actually to convince you, I am ready to institute a cash prize for anyone finding a number that could&#39;nt be expressed in the above manner. It will be a bother if the number is greater than the 32 bit limit i.e. 4294967296. So I wont do it for you, but it certainly can be expressed as a tristate. So the above exercise has convinced you that any number can be expressed in the manner given below. So this becomes a polar place value number system. Let us call it the Tristate number system. It is easier to visualize it as a scaffolding adjusting its links to reach a point on the number line.
</p>
<p align="justify">
It has all the <em>basic requisites of a number system</em>.
</p>
<p align="justify">
<strong>(a). That all numbers had a unique representation. (meaning you could not have two ways to define the same number.)</p>
<p>(b). That no number went underrepresented. There were no gaps in the entire number line till infinity.</p>
<p>(c). Two representation did not represent the same number. It is the converse of (a) </p>
<p>(d). That all symbolic representations must map to a number.(that there will be no number without any meaning)<br />
</strong><br />
At this stage, I&#39;d like to clarify to those who are still thinking that the Tristate system is nothing but a base 3 number system, that the Tristate system has no relation at all with the Base 3 number system.You can clearly see that they are not the same thing at all. They do not even have comparable number of bits to represent the same information. Base 3 is far behind. We can have all kinds of place value number system increasing the number of symbols to be used, BUT we can have only one polar place value system. This amazing property is special to the number 3. If we tried to do the same thing with any other number greater or smaller, we would have gaps or overlaps in the number line violating the requisites of a number system (c) and (b) respectively. You could attempt with 4 for instance. 4^0, 4^1, and so on. Then you would find that some numbers went unrepresented (gaps). That was about the property that came our way. Now how do we use this property ?</p>
<p>Now I shall explain why this number system is going to be more efficient in all respects, in terms of storage and transmission, in operations and algorithms and in zillions of implementations including artificial intelligence.
</p>
<h4>(a) Deducible Coding</h4>
<p align="justify">
This would be the most efficient way to send info in a 3 ary system (m-ary). Any other means to send data in a 3 ary system would employ some kind of a look up table. This would add to an overhead of having to compare a given bit stream with a huge look up table, both at the sending end and the receiving end. The Tristate system is entirely deducible at both the ends. It does not need any kind of a look up table. There is no coding and decoding overhead. I have a feeling that God is pointing this way. For instance, a 3 ary system implemented in PSK system with a 120 degree phase shift is likely to give the best results ( to detect a deviate signal&nbsp; ) for the same reason as why a tripod has maximum stability. I do not have adequate knowledge in this field but I have an intuition that this will be so. Perhaps only now have we reached the theoretical limit of information that can be packed into symbols.
</p>
<h4>(b) Simpler and Efficient Operations.</h4>
<p align="justify">
Another exciting feature that follows is the much more efficient and simplified algorithm for mathematical operations. The Tristate system appears to be the natures chosen system. While I mention the inherent simplicity of incorporating the system, you may stop to wonder how such an obvious choice had evaded us for so long. (i) Every Tristate number is inherently positive or negative. We do not need to send an extra bit to represent the sign + or &#8211; . Therefore it has cut down all the complications that we face in trying to represent a negative number in binary system. ( The 1&#39;s complement and 2&#39;s complement methods). The existing system needs a difficult algorithm to do mathematical operations on these signed numbers. For subtraction between two negative numbers for example. Since the basic operations of addition and subtraction are carried out so frequently in an average programme, the complicated algorithm leads to a considerable overhead. The tristate number cuts down on this drastically. There is only one kind of operation required: Addition for both addition and subtraction. Since the sign of the number is contained in the number itself, an addition of a positive number to negative number results in the subtraction of that number from the positive number. Hence only one set of rules suffice. (-) + (-) = + and Carry = -</p>
<p>(+) +(-) = 0<br />
(+) +(0) = +<br />
(-) +(0) = -<br />
(+) + (+) = &#8211; and Carry = +</p>
<p>This should lead to a substantial reduction to hardware required to implement these operations in a machine. Also it will be much simpler and faster. (ii) In multiplication the system lends itself easily to operations. The rules are</p>
<p>(+) * (+) = +<br />
(+) * (-) = -<br />
(-) * (-) = +</p>
<p>(iii)Division: A simple rule for division has been hard to come by so far. This is one of the reasons for withholding the publication of this theory a long while ago. It is less than complete in this one aspect. In any case the rules for divisions for all systems so far has been very complex. In this case too, we may have to resort to restoring or the non restoring division algorithm. But I have a firm belief that a simple scheme evades us till today. May be you shall help us find one. I am looking in the direction of Vedic Mathematics to show me a way to resort this issue in God&rsquo;s desired way. </p>
<p>(iv) Representation of fractional numbers. The representation of fractional numbers have always been a tricky problem in number systems. For example if we were given to express .001 in binary system, the binary system would go on generating a stream of numbers inching its value towards the desired value, but alas it could&#39;nt have reached within 99% of the desired value in the first five significant digits. Again the tristate system would be very efficient in closing on to nearest a value of a fractional number.</p>
<p>Let us begin with this hint. The summation of 3^n where n tends to minus infinity is a convergent series that equals exactly to .5.In other words, if we added an infinite string of tristate numbers after the tristate point, we could at best make up a number no greater than .5. This covers exactly half the length between 0 and 1 on the number line. This might appear unpromising at first sight, but actually this is exactly what ought to have been the case if we were to continue the tristate miracle well into the real line. We can still represent all the numbers above the value of .5 because the tristate closes in on a number from two directions. For all those numbers above .5 (say .75) we would approach the number as a result of subtracting some fractional terms from unity. This goes with the rest of the scheme and algorithm of tristate. There is no change. But as a pay off from this two pronged approach to reaching a number on the real plane is far greater resolution. By resolution I mean that we can represent fractional numbers far more accurately without running into huge strings of numbers after the tristate point (like decimal point, binary point). To make a quantitative study of this increment of resolution we will have to define certain new things. I am working on it. But if you get the idea, its enough.<br />
The discrete has become truly continuous.
</p>
<h4>(c) Other uses of the tristate approach: </h4>
<p align="justify">
The tristate system is endowed with an inherent character of zooming up and down from a value before it zeroes in on a specified value. This bi-directional oscillation can be used in algorithms for searches, because searches tend to hover over a solution area before narrowing in. Currently such hovering has to be specifically programmed. Because the tristate system is inherently endowed with this property, we can take advantage of this without having to do specific coding.
</p>
<h4>(d) Data Compression: </h4>
<p align="justify">
There is no way of compressing truly random stream of data. Any novel approach like the search of the Perpetual Motion Machine ends up with an objection called the Counting rule. I have been thinking of ways to use this special property of numbers to find a way to compress truly random data in a hitherto impossible way by beating the counting rule somehow. In any case, the tristate system implemented in a 3 ary system can reduce the bandwidth requirement in data transmission. See lossy compression below.</p>
<p><em>Possible uses of other polar place value systems.<br />
</em><br />
We mentioned earlier that other polar place value system would have gaps or overlaps. But this property itself could be used to our advantage in certain situations. <br />
In the field of artificial intelligence. In what can be called an artificially rarefied exhaustive search algorithm. Let us consider the intelligence required by us to play chess. We do not attempt to find exact solutions. We cut down our search for a good solution by pruning improbable solutions at an early stage. Looking for an exact solution would imply taking into consideration all possible permutations and expanding on them. Since it will easily exceed our processing power we deliberately rarefy an exhaustive search. While a computer is generally taught to go for an exact solution and it has to consider all the possibilities and further possibilities based on them. Very soon it faces a problem called the combinatorial explosion. There are so many combinations that the computer gets bogged down at one level of move and cannot move to the next. This results in reducing the penetrance or the reach. While the human being can clip a lot of branching and achieve greater reach even without tremendous processing powers. A polar place value system to the base of say 4 or 5 or higher will have a lot of gaps, which will make it possible for the computer to have a view of a greater amount of terrain (solution space) at first glance. The gaps will result in cutting down the actual number of possibilities to be analyzed, thus allowing better penetrance. If a particular area appears warm ( to be interesting or promising to the objective of the program ), it can always retrace back to do a truly exhaustive search of that solution space. This should normally result in better performance. And this is indeed the way we think, first getting a better overview of the problem and then moving on to the specifics. And this indeed is the secret behind the tremendous achievements made by the human mind. A polar place value system is inherently having gaps and therefore can reach a larger area of the solution space at first glance. Therefore, it will be easier to implement such algorithms using this kind of a number systems. In the field of distance communications. Say for a roving probe doing the terrain mapping over the surface of the planet Mars. Abundant information or resolution may be available with the probe but the number of bits that it can successfully send back to earth are at a premium. It is more important for the receivers on earth, to get a fair idea of a greater region than to get accurate samples of a small region. If a comparative study is done on the probability of error versus information received for the same bandwidth, the performance of the polar place value system will be found to be better. I think this can have great applications. We can make very efficient schemes of lossy compression using these other polar place value systems.
</p>
<h4><strong>Applications of the Tristate concepts in other fields.</strong><br />
</h4>
<p align="justify">
(i) Practically in any field that incorporates a differential arrangement. The optimum length of links in a scaffolding used by constructors and firemen to reach all possible floor levels. The ratings of the stepper motors required to achieve fine placement or giving finely variable torque. Or in fixing gear ratios to permit all possible speeds. Designers and technologists can find many more.<br />
(ii) Currency notes/ Credit tokens. The most economical ways to exchange money for the least number of currency notes/ coins minted.<br />
(iii) Cryptology: More complex encryption can be achieved which will resist breaking because it is non standard.<br />
(iv) Or the standard weights used by the shopkeeper from which the problem initially evolved.<br />
(v) Did you hear of a plate designed by Carl Sagan which was sent as a message from earth to distant space in a probe that was hurtling away from the Solar System at an amazing speed towards outer space. The plate was engraved with pictures and symbols that were to make some deducable meaning to an intelligent alien if it were to meet one in its journey. The information included numbers and there was a diagram to explain how those numbers worked. Can you think of a most deducible number system that would uniquely make sense to any kind of intelligent life in the universe ?</p>
<p>You could kindly write your comments to this theory to me at abhijit8086@yahoo.com. Or if you would like to give the idea publicity or be reflected in the appropriate forum, you are encouraged to do so but please keep me in picture by obtaining a written confirmation from me. </p>
<p><strong>Abhijit Bhattacharjee<br />
</strong><strong>http://abhijit.info/</strong>&nbsp;
</p>
<p align="justify">
<strong><a href="http://abhijit.info/" target="_blank">Visit Abhijit&#39;s Website</a></p>
<p></strong><em>&lt;&#8212;&#8212;&#8212; Orginal Work of Author Ends Here &#8212;&#8212;&#8212;&gt; &nbsp; </em>
</p>
<p align="justify">
<br />
Personally, I see a good potential in this theory and I played with the number system in some tricky manner.&nbsp;
</p>
<p align="justify">
<br />
Thanks.
</p>
<p><!-- google_ad_section_end(weight=ignore) --></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ruchitsurati.net/index.php/2007/08/03/the-tristate-theory-a-whole-new-number-system/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

