<?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>Aleem Bawany &#187; Web</title>
	<atom:link href="http://aleembawany.com/category/web/feed/" rel="self" type="application/rss+xml" />
	<link>http://aleembawany.com</link>
	<description>tech, web and the rest</description>
	<lastBuildDate>Sat, 05 Jun 2010 22:41:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Top 1000 Most-visited Sites on the Web</title>
		<link>http://aleembawany.com/2010/05/31/top-1000-most-visited-sites-on-the-web/</link>
		<comments>http://aleembawany.com/2010/05/31/top-1000-most-visited-sites-on-the-web/#comments</comments>
		<pubDate>Mon, 31 May 2010 13:59:51 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[New Media]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=1019</guid>
		<description><![CDATA[Google's just released list of "1000 most-visited sites on the web" is a real treat and quite interesting to analyze. It has to be one of the most accurate lists given Google's massive network reach. The list contains Unique Users (UU) and Page Views (PV). Besides Orkut, Google has not listed any of it's own sites in the list so Google News, Google Search and GMail may very well be in the top 1000 but absent from this list. I also calculated the Average Page Views (APV) to show how many pages each user visits on average on the site.]]></description>
			<content:encoded><![CDATA[<p>Google&#8217;s just released list of &#8220;<a href="http://www.google.com/adplanner/static/top1000/">1000 most-visited sites on the web</a>&#8221; is a real treat and quite interesting to analyze. It has to be one of the most accurate lists given Google&#8217;s massive network reach. The list contains Unique Users (UU) and Page Views (PV). Besides Orkut, Google has not listed any of it&#8217;s own sites in the list so Google News, Google Search and GMail may very well be in the top 1000 but absent from this list. I also calculated the Average Page Views (APV) to show how many pages each user visits on average on the site.</p>
<p>Interested readers may view a dynamically sortable table of the complete list of <a href="http://aleembawany.com/topsites/">top 1000 most visited sites on the web</a> which also has APV added (<strong>Warning</strong>: on slow computers it may take a while to load or crash your browser since it&#8217;s a long list that requires Javascript processing).</p>
<p>I used it to gather the following data for sites in the News category.</p>
<h2 id="toc-news-current-events">News &amp; Current Events</h2>
<p>This category includes sites with an online and television presence, covering current and breaking news.</p>
<ul>
<li><a href="http://bbc.co.uk">BBC</a> (#43) with 45 million UU and 56 APV, the highest in the overall News category</li>
<li><a href="http://ifeng.com/">ifeng.com</a> (#55) in Chinese/Mandarin</li>
<li><a href="http://cnn.com/">CNN</a> (#64) with 34 million UU and 38 APV</li>
<li><a href="http://digg.com/">Digg</a> (#252) is also impressive given that its a community driven news aggregator that runs automatically</li>
<li><a href="http://foxnews.com/">FoxNews</a> (#279) with 11 million UU and 8 APV</li>
</ul>
<h2 id="toc-newspapers">Newspapers</h2>
<p>This category includes the traditional print newspapers complemented by an online presence</p>
<ul>
<li><a href="http://www.nytimes.com/">NYTimes</a> (#83) takes the top spot with 26 million UU and 23 APV</li>
<li><a href="http://yomiuri.co.jp/">Yomiuri</a> (#213) with 20 APV</li>
<li><a href="http://dailymail.co.uk/">Daily Mail</a> (#236) with 22 APV</li>
<li><a href="http://wsj.com/">WSJ</a> (#277) with 15 APV</li>
<li><a href="http://mainichi.jp/">Mainichi</a> (#287) with 7 APV</li>
<li><a href="http://guardian.co.uk/">Guardian</a> (#310) with 16 APV</li>
</ul>
<h2 id="toc-business-news">Business News</h2>
<ul>
<li><a href="http://ce.cn/">CE.CN</a> (#500) with 7.4 million UU and 5 APV giving it 34 million monthly PV</li>
<li><a href="http://forbes.com/">Forbes</a> (#633) with 6.1 million UU and 18 APV giving it 110 million monthly PV</li>
</ul>
<h2 id="toc-local-news">Local News</h2>
<p>This category includes online news sites which focus on national coverage<a href="http://ig.com.br/"></a></p>
<ul>
<li><a href="http://ig.com.br/">iG.com.br</a> (#477) out of Brazil</li>
<li><a href="http://zjol.com.cn/">zjol.com.cn</a> (#746) out of China</li>
</ul>
<h2 id="toc-social-networks">Social Networks</h2>
<p>Of the top 1000 sites, the ones with the highest APV are comprised primarily of social networking sites along with a few classifieds and shopping sites. This makes sense because people spend a lot of time on social networking sites viewing a lot of pages.</p>
<h2 id="toc-page-views">Page Views</h2>
<p>Facebook is the grand daddy of all websites. Not only does it have the highest number of UU at 540 million, its PV count gets even more impressive with an APV count of 1056. Facebook gets a total of 570 billion page views per month which is more than all the next 30 websites combined! Yahoo web portal is a paltry second with 70 billion page views from it&#8217;s 490 million unique users.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2010/05/31/top-1000-most-visited-sites-on-the-web/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Express Tribune</title>
		<link>http://aleembawany.com/2010/04/13/the-express-tribune-3/</link>
		<comments>http://aleembawany.com/2010/04/13/the-express-tribune-3/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 15:23:41 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[New Media]]></category>
		<category><![CDATA[Pakistan]]></category>
		<category><![CDATA[Technophilia]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=974</guid>
		<description><![CDATA[What on the onset seemed quite trivial actually turned out to be quite hard. <a href="http://tribune.com.pk/">The Express Tribune</a> launched just 2 days ago with a stunning paper and a web portal to match. Building large scale systems like The Express Tribune news portal and turning it around in 6 months requires a team of determined masochists and some really quick thinking.]]></description>
			<content:encoded><![CDATA[<p>What on the onset seemed quite trivial actually turned out to be quite hard. <a href="http://tribune.com.pk/">The Express Tribune</a> launched just 2 days ago with a stunning paper and a web portal to match.</p>
<p>Building large scale systems like The Express Tribune news portal and turning it around in 6 months requires a team of determined masochists and some really quick thinking. One has to think about scalability, performance, security, architecture and pliability of the product. One also has to think about usability, information architecture and layouts. About user interactivity, community engagement and publication workflows. Integration with television and print and a coherent new media strategy.</p>
<p>But it&#8217;s here and it&#8217;s far from over. Going in, I was confident that we would easily come out ahead of the competition (whom I have written about <a href="http://aleembawany.com/2008/08/28/dawn-com-barely-worth-the-effort/">here</a> and <a href="http://aleembawany.com/2010/02/07/jang-news-advertising-vs-user-experience/">here</a>) but I never thought I would have so much fun doing it.</p>
<p>The Express Tribune website uses some existing platforms and our developer toolkit is quite powerful, but to get to where we wanted to go, we got neck deep in every aspect of the system.</p>
<p>Beyond being just a pretty website, it has some behind the scenes features where it really shines out. This is where the competition has a lot of catching up to do. For example, assigning headlines and stories to sections or updating the page layout happens directly from the section itself, rather than going in to some specialized administrative screen. The image management and carousels are first class features and not just an after thought. The News in Pictures and slide shows can be done in under 5 minutes. The pages load blazingly fast, because we optimized not only the caching mechanisms but also the web server, database server, application server and even the operating system.</p>
<p>The user interface follows some hard principles. For example, the comment preview feature is painstakingly simple and dynamic so users know exactly how their words will appear. The submit button is below the comment preview by design, so the user is forced to preview on his way to the submit button. The design follows a horizontal rhythm using grid-based layouts. The weather widget updates the weather without having to refresh the page and on the back end we do some very specific caching so we can handle thousands of users, yet provide the latest weather updates or auto updating stock charts. The alerts ticker is directly linked to the Express 24/7 television station which requires some trickery on the part of both, the television platform as well as the web platform.</p>
<p>The interesting bits about strategy are something I cannot talk about other than to say that if the website works well for you and you find yourself interacting more and more, it&#8217;s because we put the user first. And in the short and long term both, our strategy will allow us to surpass the competition and out-pace them so we maintain the lead.</p>
<p>With internet penetration growing the way it is, I have no doubt that The Express Tribune portal will provide common ground for a lot of avid readers and have interesting side effects.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2010/04/13/the-express-tribune-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Understanding Abstract Classes in PHP</title>
		<link>http://aleembawany.com/2010/04/03/understanding-abstract-classes-in-php/</link>
		<comments>http://aleembawany.com/2010/04/03/understanding-abstract-classes-in-php/#comments</comments>
		<pubDate>Fri, 02 Apr 2010 19:44:20 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=934</guid>
		<description><![CDATA[Abstract classes are an often misunderstood feature of PHP object-oriented programming (OOP) and the source of confusion when considered versus an Interface. The obvious reason for using an Interface is that a child class can implement multiple interfaces but extend only a single abstract class. However, if multiple inheritance is not required then people often go with abstract classes just because they provide the option of later adding base functionality within the abstract class. This is not entirely unreasonable but the reasons for creating abstract classes should be more than that.]]></description>
			<content:encoded><![CDATA[<p>Abstract classes are an often misunderstood feature of PHP object-oriented programming (OOP) and the source of confusion when considered versus an Interface. The obvious reason for using an Interface is that a child class can implement multiple interfaces but extend only a single abstract class. However, if multiple inheritance is not required then people often go with abstract classes just because they provide the option of later adding base functionality within the abstract class. This is not entirely unreasonable but the reasons for creating abstract classes should be more than that.</p>
<h2 id="toc-why-use-abstract-classes">Why Use Abstract Classes?</h2>
<p>An <em>Abstract</em> class provides concrete base functions as well as abstract functions that must be implemented by <em>concrete child</em> classes—binding them into a contract so to speak, if they wish to make use of the base functionality.</p>
<p>This is a subtle but important point and this is where abstract classes really shine. They can call abstract functions from within base concrete functions. Jumping straight to an example is the clearest way to explain this.</p>
<pre class="prettyprint">abstract class Animal {
  function greeting() {
    $sound = $this-&gt;sound();      // exists in child class by contract
    return strtoupper($sound);
  }
  abstract function sound();      // this is the contract
}

class Dog extends Animal {
  function sound() {              // concrete implementation is mandatory
    return &quot;Woof!&quot;;
  }
}

$dog = new Dog();
echo $dog-&gt;greeting();            // WOOF!</pre>
<p>This opens up a whole lot of interesting possibilities. For example, you can write a <code>drive()</code> function that calls <code>$this->start(); $this->accelerate();</code> in an abstract class. Then create a motorcycle class that defines its own <code>start()</code> and <code>accelerate()</code> functions that may be different from those in the car class. In turn, the motorcycle and car can both be driven by just calling <code>drive()</code> without having to implement it locally.</p>
<h2 id="toc-characteristics-of-abstract-classes">Characteristics of Abstract Classes</h2>
<p>Make a note of these characteristics to lock down your understanding of abstract classes:</p>
<ol>
<li>Single inheritance. Child classes can extend only one class at a time. </li>
<li>Abstract classes cannot be instantiated &#8212; no <code>new Animal();</code> </li>
<li>Abstract classes can define class variables of type <em>const</em> only. </li>
<li>Abstract class A can be extended by another abstract class B. Abstract class B can implement none or any of the abstract functions in A. </li>
<li>In the previous case, a child class C which extends abstract class B must implement all abstract functions in B as well as the abstract functions in A which have not already been implemented in B. </li>
<li>The signature of the concrete functions and abstract functions must be the same. However, if an abstract function is defined as <code>abstract function speak($greeting);</code> then it is okay to implement it as <code>function speak($greeting, $shout = FALSE)</code> but not <code>function speak($greeting, $shout)</code>. </li>
<li>The visibility of functions in the child classes must be the same or <em>less restrictive</em> than the parent class. Thus, a <code>protected</code> abstract function can be implemented as either <code>protected</code> or <code>public</code> but not <code>private</code>. </li>
<li>Declaring functions as <code>static abstract</code> throws a strict warning in PHP 5.2 or earlier, however, as of PHP 5.3 this is allowed.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2010/04/03/understanding-abstract-classes-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Jang News: Advertising vs User Experience</title>
		<link>http://aleembawany.com/2010/02/07/jang-news-advertising-vs-user-experience/</link>
		<comments>http://aleembawany.com/2010/02/07/jang-news-advertising-vs-user-experience/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 15:45:08 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[New Media]]></category>
		<category><![CDATA[Pakistan]]></category>
		<category><![CDATA[Technophilia]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=845</guid>
		<description><![CDATA[The <a href="http://jang.com.pk/" title="Jang News Online">Jang News</a> website is one that just keeps getting worse with each passing day. It's lacklustre and shows absolutely no concern for its readers or the news that it serves. The website is a big hoarding with no less than <strong>19 advertisements</strong> on the website's front page while at the same time carries <strong>less than 100 words of actual news</strong>. And it looks really ugly to boot.]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://jang.com.pk/" title="Jang News Online">Jang News</a> website is one that just keeps getting worse with each passing day. When I wrote a review of <a href="/2008/08/28/dawn-com-barely-worth-the-effort/">Dawn.com Beta website launch</a>, I highlighted their technical and interface shortcomings but the Jang News&#8217; website is not worthy of even that. It&#8217;s lacklustre and shows absolutely no concern for its readers or the news that it serves.</p>
<p>The website is a big hoarding with no less than <strong>20 advertisements</strong> on the front page while at the same time carries <strong>less than 100 words of actual news</strong>. And it looks really ugly.</p>
<p><a href="http://aleembawany.com/wp-content/uploads/2010/02/jang-news-advertising.jpg" title="Jang News Online Website"><img src="http://aleembawany.com/wp-content/uploads/2010/02/jang-news-advertising.jpg" alt="" title="Jang News Online Advertisements" width="600" height="597" /></a></p>
<p>This is what happens when you <strong>just don&#8217;t care about the readers</strong>. This is what happens when designers develop, developers design, business units dictate the roadmap and talent in general lacks. This is also what happens when you just don&#8217;t understand <strong>interaction design</strong>, information architecture, usability or have been oblivious to the paradigm shifts in online advertising and technological trends. This screen capture of the Jang News website clearly highlights all this.</p>
<p>The actual news content is highlighted in green boxes while the rest of the page is mostly advertisements. All ad slots highlighted in red are available for sale while unsold ad space is used for in-house products. The <a href="http://www.jang.com.pk/ad-tariff/newtariff/index.html">advertising tariffs</a> section of the website indicates the type of ads available for sale on Jang News Online which includes video and expandable ads at a premium. The <strong>annoying expandable ads</strong> block access to the news until readers close them (shown in the screen capture) while video ads block the rest of the page because they take so long to load (Pakistan has very low broadband penetration in any case).</p>
<p>Jang News Online gets a considerable amount of traffic because the Jang News Group has entrenched itself as the face of news over the past 70 years that it has been around&#8211;a time during which it enjoyed <strong>little or no competition</strong> which helps explain their complacency.</p>
<p>Now, I am not even sure why an advertiser would want to publish one ad amongst 20 when it&#8217;s well known that users develop <a href="http://www.google.com/search?q=banner+blindness">banner blindness</a> and moreover the website&#8217;s ad space is extremely diluted and the screen interface is so cluttered.</p>
<p>The page reminds me of the days popup ads ran rampant until readers expressed rage and all major browsers (Internet Explorer, Firefox, Safari, et al) reacted by featuring popup blockers to put an end to it all. Unfortunately, in Jang&#8217;s case it&#8217;s not easy to block the spam. The website&#8217;s front page is practically an <strong>online hoarding</strong> which seems to take it&#8217;s cue from the <a href="http://www.milliondollarhomepage.com/">million dollar homepage</a> (whose sole purpose is to show advertisements) rather than a news site. One may easily pass this off as spam in its current state.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2010/02/07/jang-news-advertising-vs-user-experience/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Online Strategy &amp; Development in a Nutshell</title>
		<link>http://aleembawany.com/2010/01/28/online-strategy-development-in-a-nutshell/</link>
		<comments>http://aleembawany.com/2010/01/28/online-strategy-development-in-a-nutshell/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 09:24:09 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[Technophilia]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=825</guid>
		<description><![CDATA[Microsoft Innovation Center hosted the Microsoft Web Days session today where I gave a talk about online strategy and development (in a nutshell). Even thought it was in a nutshell, I slipped in some details which meant skimming over a lot of other things during latter part of the brief 30 minute presentation. The presentation covered frameworks, interaction design, business models, strategies, tools, trends and user experience among other things.]]></description>
			<content:encoded><![CDATA[<p>Microsoft Innovation Center hosted the Microsoft Web Days session today where I gave a talk about online strategy and development (in a nutshell). Even thought it was in a nutshell, I slipped in some details which meant skimming over a lot of other things during latter part of the brief 30 minute presentation. The presentation covered frameworks, interaction design, business models, strategies, tools, trends and user experience among other things.</p>
<p>There are some valuable lessons in this for all budding web developers and web entrepreneurs.</p>
<p><object style="margin:0px" width="505" height="415"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=onlinestrategyanddevelopmentinanutshell-100127144415-phpapp02&#038;stripped_title=online-strategy-and-development-in-a-nutshell&#038;rel=0" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=onlinestrategyanddevelopmentinanutshell-100127144415-phpapp02&#038;stripped_title=online-strategy-and-development-in-a-nutshell&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="505" height="415"></embed></object></p>
<p>Download PowerPoint: <a href="/wp-content/uploads/2010/01/Online-Strategy-and-Development-in-a-Nutshell.ppt">Online Strategy and Development in a Nutshell</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2010/01/28/online-strategy-development-in-a-nutshell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tr.im Goes Open &#8211; Bad Move or Marketing Ploy?</title>
		<link>http://aleembawany.com/2009/08/17/tr-im-goes-open-bad-move-or-marketing-ploy/</link>
		<comments>http://aleembawany.com/2009/08/17/tr-im-goes-open-bad-move-or-marketing-ploy/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 23:25:08 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[Technophilia]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=802</guid>
		<description><![CDATA[Tr.im is a URL shortening services useful for applications like Twitter where the length of posts is restricted to around 140 letters and short URLs are desirable. Recently tr.im announced that it was going out of business and shutting down but soon after they reversed their position and Eric Woodward offered to bear the costs of operations out of his own pocket if donations fell short. A move that is probably even worse than shutting down.]]></description>
			<content:encoded><![CDATA[<p><a title="Trim URL Shortener" href="http://tr.im/">Tr.im</a> is a URL shortening services that converts your URL from <code>http://aleembawany.com/2009/08/17/tr-im-goes-open-bad-move-or-marketing-ploy/</code> to something like <code>http://tr.im/wzz0</code>. It&#8217;s useful for services like Twitter where the length of posts is restricted to around 140 letters.</p>
<p>In a seemingly abrupt move, tr.im recently announced the <a href="http://blog.tr.im/post/159489555/tr-im-to-december-31-2009">decision to shut down</a> at the end of this year blaming the <a href="http://bit.ly/">bit.ly</a> and Twitter partnership for driving them out of business. I have not used either service other than for test driving so I don&#8217;t have a bias either way but it makes sense for Twitter to go with best of the breed so it is unclear why tr.im needs to place the blame with either bit.ly or Twitter. The situation was pareto efficient and one or the other had to lose out. It makes sense for Twitter to partner with or acquire such a service because it is complimentary to their business (tiny posts with tiny URLs).</p>
<p>Soon after announcing their intent to go out of business, tr.im reversed their position and Eric Woodward offered to bear the <a href="http://blog.tr.im/post/165049236/tr-im-to-be-community-owned">costs of operations out of his own pocket</a> if donations fell short&#8211;a move that is even worse than going out of business.</p>
<h2 id="toc-revenue-model">Revenue Model</h2>
<p>The revenue model suggests that for the most part, such a service is very difficult to sustain. The revenue model for URL shortening services would depend either on showing disruptive advertisements or tracking user patterns and selling intelligence.</p>
<p>In the former case, users would probably stop using the service if they saw an ad before being redirect to long URL. In the latter case, tr.im would need considerable market share to track behavioural data.</p>
<p>Tr.im shot itself in the foot by claiming it will simply go belly up because the business is bad. There goes their chance of getting acquired for a good price.</p>
<p>All this is offset by the fact that it allowed tr.im to receive a lot of media attention and might drive up usage but smart users will shy away from a service that&#8217;s on life support and business continuity is of utmost importance. The smarter strategy was to get acquired much like bit.ly did.</p>
<h2 id="toc-why-go-open">Why go open?</h2>
<p>The technical challenge of converting long URLs to short ones is trivial so the value-proposition to the community is not that great but let&#8217;s assume that since it&#8217;s free it&#8217;s good. The problem then again is that it will encourage users to create their own competing services to bit.ly and since the revenue model for the most part does not have a compelling monetization strategy, these services will eventually go out of business and intensify the link-rot problem.</p>
<p>The primary motivation for going open seems to be the move toward donations where the community would donate code as well as money to keep the servers running for the millions of links that will accumulate over time. This works well for Wikipedia because it is a natural monopoly and can fall back on ads if needed. And again, Wikipedia has completely different dynamics compared to tr.im which functions simply to shorten the length of links with equal or better services already available that pose a lesser risk of going bust.</p>
<h2 id="toc-a-nasty-time-bomb">A Nasty Time Bomb</h2>
<p>When Eric Woodward proposes that he will fund this from his own pocket if donations fall short, the community should be concerned. What is something happens to Eric? Does he leave behind a trust fund? Not only that but the costs are ever-increasing because all links will need to be supported for all of time or thousands if not millions of links will break.</p>
<p>The longer the service stays in operation, the greater the risk it poses. If it goes out of business 2 years from now it might end taking out a couple million URLs with it which will be even worse than if it went out of business today.</p>
<p>So the costs will be ever-increasing, the risks will also be ever-increasing and there is no good revenue model to sustain the service. In fact if it becomes community owned, all data will be free so tr.im cannot depend on behavioural tracking data as a revenue strategy. Tr.im will continue to be a burden on the community and not only that, but if other unsustainable services come up replicating its code, the link rot problem will get compounded. And all those people who make donations will see their money go to waste when they realize the tr.im will need piles of cash, month after month with no other source of cash flow.</p>
<p>I hope I am wrong about this.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2009/08/17/tr-im-goes-open-bad-move-or-marketing-ploy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSON Serializers In .NET</title>
		<link>http://aleembawany.com/2009/05/22/json-serializers-in-net/</link>
		<comments>http://aleembawany.com/2009/05/22/json-serializers-in-net/#comments</comments>
		<pubDate>Fri, 22 May 2009 16:22:59 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[Technophilia]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=696</guid>
		<description><![CDATA[<p>I was introduced to the various serialization options in .NET while trying to build the <a href="http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/">JSON and XML</a> filters for ASP.NET MVC. In this post I'll take a look at the different JSON serializers available in .NET and the reasons to pick one over the other.</p>
]]></description>
			<content:encoded><![CDATA[<p>I was introduced to the various serialization options in .NET while trying to build the <a href="http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/">JSON and XML filter for ASP.NET MVC</a>. In this post I&#8217;ll take a look at the different JSON serializers in .NET and the reasons to pick one over the other.</p>
<h2 id="toc-javascriptserializer">JavaScriptSerializer</h2>
<p>The <a title="JavaScriptSerializer" href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx"><code>JavaScriptSerializer</code></a> lives in the <a title="System.Web.Script.Serialization namespace" href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.aspx">System.Web.Script.Serialization</a> namespace and the usage is fairly straight forward for serialization:</p>
<pre class="prettyprint">JavaScriptSerializer serializer = new JavaScriptSerializer();
String json = serializer.Serialize(data);</pre>
<p>For deserialization however, there is a minor annoyance in that the deserializer accepts a generic type along with the content:</p>
<pre class="prettyprint">serializer.Deserialize&lt;T&gt;(String s)</pre>
<p>which can be a problem if the type T is not known at compile time and needs to be dynamic. The work around is a bit ugly as I <a title="Invoke JavaScriptSerializer with Dynamic Type" href="http://stackoverflow.com/questions/856665/how-to-turn-a-type-instance-into-a-generic-type-argument">learnt</a> because it uses reflection to create a generic method but it works:</p>
<pre class="prettyprint">var result = typeof(JavaScriptSerializer).GetMethod("Deserialize")
             .MakeGenericMethod(JsonDataType)
             .Invoke(serializer, new object[] { inputContent });</pre>
<p>The <code>JavaScriptSerializer</code> is excellent for general purpose serialization and deserialization, however, one downside is that it cannot handle circular references.</p>
<p>A useful feature of the <code>JavaScriptSerializer</code> is that you can also implement a custom <a title="JavaScriptConverter custom serialization" href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptconverter.aspx"><code>JavaScriptConverter</code></a> and pass that in to <code>JavaScriptSerializer</code> for fine-grained control over the serialization/deserialization. However, for it to be really useful you need to know the types at compile time and have references to those types. This really limits the usefulness of this feature because by referencing those classes your code becomes tightly coupled so you cannot easily use it in something like an MVC filter.</p>
<p>The <code>JavaScriptSerializer</code> includes all public fields and properties for serialization by default which makes it useful when working with auto-generated classes or if you don&#8217;t have access to the source. This is different from how <code>DataContractJsonSerializer</code> works.</p>
<h2 id="toc-datacontractjsonserializer">DataContractJsonSerializer</h2>
<p>The <a title="DataContractJsonSerializer in .NET" href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx"><code>DataContractJsonSerializer</code></a> lives in the <a title="System.Runtime.Serialization.Json namespace" href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.aspx">System.Runtime.Serialization.Json</a> namespace. Unlike the <code>JavaScriptSerializer</code>, the <code>DataContractJsonSerializer</code> is a contract-based serializer so classes or members need to have the <code><a title="DataContract Attribute for serialization with DataContractSerializer" href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx">[DataContract]</a></code>, <code><a title="DataMember Attribute for serialization with DataContractSerializer" href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx">[DataMember]</a></code> or the <code><a title="Serializable Attribute" href="http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx">[Serializable]</a></code> attribute.</p>
<pre class="prettyprint">[Serializable]
class Person {
    public String Name;
    public Int32 Age;
}

...

String json;
using (var stream = new MemoryStream()) {
    DataContractJsonSerializer serializer =
       new DataContractJsonSerializer(data.GetType());
    serializer.WriteObject(stream, data);
    json = Encoding.UTF8.GetString(stream.ToArray());
}</pre>
<p>And for deserialization:</p>
<pre class="prettyprint">using(var stream = new MemoryStream(Encoding.Unicode.GetBytes(json)) {
    Object data = serializer.ReadObject(stream);
}</pre>
<p>Since <code>DataContractJsonSerializer</code> is contract based and relies on attributes, it is not particularly suitable for auto-generated classes (unless they have these attributes) or when source is not accessible because the relevant attributes <a title="DataMember Attribute at Runtime for DataContractSerializer" href="http://stackoverflow.com/questions/713543/set-datacontracts-datamember-attributes-during-runtime">cannot be added at runtime</a> as far as I know. However, for other situations attributes are an easy way to control the serialization aspects.</p>
<p>The most compelling feature of the <code>DataContractJsonSerializer</code> is that it can handle complex object graphs with circular references. This makes it particularly useful with the <a title="New Features in Entity Framework 4.0" href="http://aleembawany.com/2009/05/17/new-features-in-entity-framework-40-v2/">Entity Framework 4.0</a> which now support T4 templates allowing required <code>[Serializable]</code> or <code>[DataMember]</code> attributes to be added to auto-generated classes.</p>
<p><strong>Update:</strong> In .NET 3.5 SP1, DataContractSerializer added support for <a href="http://www.pluralsight.com/community/blogs/aaron/archive/2008/05/13/50934.aspx">classes without attributes</a> (or POCO objects).</p>
<h2 id="toc-json-in-mvc">Json in MVC</h2>
<p>The <a title="ASP.NET MVC Json Serializer" href="http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.json.aspx">System.Web.Mvc</a> namespace contains the <code>Json</code> function intended for use within ASP.NET MVC. There is no real reason to use it outside of ASP.NET MVC when <code>JavaScriptSerializer</code> and <code>DataContractJsonSerializer</code> are available. This function makes it extremely easy to serialize objects to a JSON string. It is not intended for deserialization, however, serialization is just one call:</p>
<pre class="prettyprint">String content = Json(data);</pre>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2009/05/22/json-serializers-in-net/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>New Features in Entity Framework 4.0 (V2)</title>
		<link>http://aleembawany.com/2009/05/17/new-features-in-entity-framework-40-v2/</link>
		<comments>http://aleembawany.com/2009/05/17/new-features-in-entity-framework-40-v2/#comments</comments>
		<pubDate>Sun, 17 May 2009 09:02:35 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[Technophilia]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=684</guid>
		<description><![CDATA[<p>Entity Framework 4.0 is just around the corner and it will bring some long awaited relief. I previously wrote and explained the issues around <a title="POCO and Persistence Ignorance in the Entity Framework" href="http://aleembawany.com/2009/04/06/persistence-ignorance-in-adonet-entity-framework/">Persistence Ignorance and POCO</a> as they apply to the Entity Framework. So obviously I'm quite excited about migrating from the interim EFPocoAdapter over to EF 4.0. Let's take a quick look at the new features in Entity Framework 4.0.</p>]]></description>
			<content:encoded><![CDATA[<p>Entity Framework 4.0 is just around the corner and it will bring some long awaited relief. I previously wrote and explained the issues around <a title="POCO and Persistence Ignorance in the Entity Framework" href="http://aleembawany.com/2009/04/06/persistence-ignorance-in-adonet-entity-framework/">Persistence Ignorance and POCO</a> as they apply to the Entity Framework. So obviously I&#8217;m quite excited about migrating from the interim EFPocoAdapter over to EF 4.0. Let&#8217;s take a quick look at the new features in Entity Framework 4.0.</p>
<h2 id="toc-poco-support">POCO Support</h2>
<p>If you are not up to date on POCO, quickly read up on <a title="Entity Framework support for POCO" href="http://aleembawany.com/2009/04/06/persistence-ignorance-in-adonet-entity-framework/">POCO and Persistence Ignorance</a> first. Entity Framework 4.0 has full support for POCO or Plain Old CLR Objects.</p>
<p>If you have a class called Person with name, address and phone number then that&#8217;s how it will stay. It will not have EntityKey or some other such properties. It does not need to implement any interface specific to Entity Framework nor does it need to add any special attributes on properties and methods.</p>
<p>You can pass this plain object around much more cleanly and your domain logic is not polluted with any persistence code. This is also useful for Test Driven Development (TDD)  or migrating out of EF to another framework down the line.</p>
<h2 id="toc-entity-model-designer-improvements">Entity Model Designer Improvements</h2>
<p>Previously you had to design the database schema in SQL Server and then import that into the Entity Designer. With 4.0 you can build the <a title="Entity Framework Model First" href="http://blogs.msdn.com/efdesign/archive/2008/09/10/model-first.aspx">model first</a> in the Entity Designer and generate your database and classes from there.  Alternately a lot of DDD (Domain Driven Design) folks prefer to hand code their model classes. Since those classes end up being POCO and EF has full support for POCO, it works out quite well for everyone.</p>
<h2 id="toc-t4-templates">T4 templates</h2>
<p>Currently the Entity Designer generates classes from models by using EntityClassGenerator which provides little to no control over the generated classes. In 4.0 you will have <a title="T4 templates" href="http://msdn.microsoft.com/en-us/library/bb126445.aspx">T4 templates</a> which provide for greater control over the generated classes with <a title="T4 Templates for Entity Framework" href="http://blogs.msdn.com/efdesign/archive/2009/01/22/customizing-entity-classes-with-t4.aspx">richer functionality</a> like adding attributes to properties or having the generated classes implement a custom interface.</p>
<p>T4 templates are used not only to generate classes but also to generate tables if you choose to start off by building the models first. For example, by default the mapping is table-per-type which can be overridden through T4 templates to produce a table-per-hierarchy schema. You can also add prefixes to the generated table names and so on.</p>
<h2 id="toc-self-tracking-entities-and-n-tier-applications">Self Tracking Entities and N-Tier applications</h2>
<p>Self tracking entities are a very cool feature of the Entity Framework that allow for N-tier applications. Currently when you have entities on which you wish to track changes, the object context does that for you. However, the object context only exists in the current tier and if you decide to pass that object around to other tiers where the context is not present, you cannot track the entities any more. For example, if you pass the Person object to the UI layer which presents it to the user for modification, those modifications are not being tracked because the object context is not available in the UI tier. N-tier support can now handle this scenario quite elegantly.</p>
<p>One way to do this is to generate <strong>self-tracking entities</strong> as these entities have logic to track changes within. If the UI modifies the Person object&#8217;s address, the Person object will now contain information on how it&#8217;s been modified because it is self-tracking. When you pass the Person object back to the data tier, the object can easily relay what&#8217;s changed and the context can use this to persist the object.</p>
<p>Of course, this means that the object is not POCO any more because it has logic to track changes within itself so there is yet another approach. You can pass the POCO object back to the Entity Framework and attach it to the context which can then do a diff on the object and the original object to determine what&#8217;s changed. This requires more processing obviously.</p>
<h2 id="toc-proxy-tracking">Proxy Tracking</h2>
<p>Besides diff&#8217;ing the POCO entities or using self-tracking entities for change detection, another approach is provided by the Entity Framework 4.0 which is proxy tracking. It provides the benefits of POCO without the performance implications of doing a diff (to check what&#8217;s changed each time the POCO object is re-attached to the context) albiet it cannot be used in an n-tier scenario.</p>
<p>If using proxies to track changes, EF sets up proxy classes to communicate with your POCO classes. These proxy classes inherit from the POCO classes and any property getter/setter calls are still made to the POCO class but through the proxy class. This allows the Entity Framework to stay in sync with entities at all times. You do however need to be a bit careful if you are going to serialize these objects because the resulting output could be a proxy object (though easily remedied by calling something like EFPocoAdapter&#8217;s ProxiesToPoco() equivalent in EF 4.0).</p>
<h2 id="toc-conclusion">Conclusion</h2>
<p>This is going to be a big release for EF to bring it in line with the other major ORMs out there. The MVC community right now favors Linq to SQL but hopefully we&#8217;ll see more ASP.NET MVC + Entity Framework projects coming out.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2009/05/17/new-features-in-entity-framework-40-v2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Persistence Ignorance in ADO.NET Entity Framework</title>
		<link>http://aleembawany.com/2009/04/06/persistence-ignorance-in-adonet-entity-framework/</link>
		<comments>http://aleembawany.com/2009/04/06/persistence-ignorance-in-adonet-entity-framework/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 12:25:40 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[Technophilia]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=625</guid>
		<description><![CDATA[Serializing objects within the Entity Framework is a common enough scenario that I expected to work around it farily easily. Because as it turned out, the serialized objects only contained some additional undesirable key/value pairs that I did not expect. This is when I first got introduced to Persistence Ignorance.]]></description>
			<content:encoded><![CDATA[<div class="toc">
<ol>
<li><a href="#toc-persistence-ignorance">Persistence Ignorance</a></li>
<li><a href="#toc-single-responsibility-principle">Single Responsibility Principle</a></li>
<li><a href="#toc-domain-driven-design">Domain Driven Design</a></li>
<li><a href="#toc-an-interim-solution">An Interim Solution</a></li>
</ol>
</div>
<p>I previously published a <a href="http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/">JSON / POX Filter</a> for MVC developers working with RESTful services. It works really well in that it allows a Controller Action to speak two additional languages (JSON and XML) other than View rendition without requiring any extra modifications. Everything was fine until I pulled out Linq to SQL and plugged in Entity Framework and got an education on a variety of issues with the framework.</p>
<h2 id="toc-persistence-ignorance">Persistence Ignorance</h2>
<p>Serializing objects within the Entity Framework is a common enough scenario that I expected to work around it farily easily. More so because the serialized objects only contained some additional undesirable key/value pairs that I did not expect. This is when I first got introduced to Persistence Ignorance.</p>
<p>In the Entity Framework an object generated from the Persons table for example contains not only the properties and relationships of that table (such as Age and Name) but also has additional properties used for tracking changes to the object (such as EntityState). In my scenario, serializing the entity object ought to have resulted in a plain object representation (JSON format shown):</p>
<pre class="prettyprint">// Plain Old CLR Object
{"Id":1, "Name":"John"}</pre>
<p>But instead I saw this:</p>
<pre class="prettyprint">// Entity Object
{"Id":1, "Name":"John",
 "EntityState":2, "EntityKey": {"EntitySetName":"Persons",
    "EntityContainerName":"PersonEntities","EntityKeyValues":
     [{"Key":"Id","Value":1}],"IsTemporary":false}}</pre>
<p>In laymen&#8217;s terms Persistence Ignorance is a design principle which suggests that the underlying object hide the details of how it is persisted so you can ignore it and work with a simple object. The term &#8220;ignorance&#8221; suggests that this behaviour be <em>encapsulated</em> which is a tenet of Object Oriented design.</p>
<h2 id="toc-single-responsibility-principle">Single Responsibility Principle</h2>
<p>Instead, the Entity Object has additional properties used by the Entity Framework for managing data persistence. An object that plainly represents the Person table and does not contain any additional service-level properties and functions is called a Plain Old CLR Object or POCO. The Entity Object violates the Single Responsibility Principle because other than representing a Person it takes on the additional responsibility of managing data persistence.</p>
<p>Albeit, this makes it very convenient for the Entity Framework to persist the object in the database if, for example, you make modifications to the Person object and save it back to the database. Because the state information is stored within the object itself, the Entity Framework easily knows if the object has changed (by looking at the EntityState property) and what changes were made. It can then update the appropriate fields in the database. Even though this makes things easy for the Entity Framework, it is clearly a big second responsibility tacked on to what should be a plain old Person object. Besides, developers need not be confused by nor concerned with lower level implementation details of state and persistence. Consequently, the Entity Framework recognizes and intends to fix this in Version 2 which will support POCO and Persistence Ignorance.</p>
<h2 id="toc-domain-driven-design">Domain Driven Design</h2>
<p>Lack of POCO objects means that developers are left dealing with an Entity Object and while for me this started off with a naive problem of serializing a Person object, the actual issue has further implications. My over simplified understanding of Domain Driven Design is that domain objects should be Plain Old CLR Objects and should encapsulate only domain logic. So for example, if you are building a warehousing application, the objects used to represent the warehouse domain should only encapsulate functionality within the warehouse (such as orders, storage and delivery). Anything more in the objects (such as database persistence) and the application breaks the Domain Driven Design model. It gets much harder to manage or extend, and Separation of Concerns is lost. For further discussion Ian Cooper&#8217;s article on <a href="http://codebetter.com/blogs/ian_cooper/archive/2008/06/26/the-criticism-of-the-entity-framework-is-not-just-around-domain-driven-design.aspx">Entity Framework and Domain Drive Design</a> provides an interesting and insightful background on this issue.</p>
<h2 id="toc-an-interim-solution">An Interim Solution</h2>
<p>The <a href="http://code.msdn.microsoft.com/EFPocoAdapter">EFPocoAdapater</a> is just what the name suggests &#8212; a POCO adapter for the Entity Framework which solves the issues outlined above. The EFPocoAdapter currently serves as a sort of staging platform for supporting these scenarios until they become available in version 2 of the Entity Framework, at which time EFPocoAdapter will be made obsolete.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2009/04/06/persistence-ignorance-in-adonet-entity-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC &#8211; Create easy REST API with JSON and XML</title>
		<link>http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/</link>
		<comments>http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/#comments</comments>
		<pubDate>Fri, 27 Mar 2009 18:03:34 +0000</pubDate>
		<dc:creator>Aleem</dc:creator>
				<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://aleembawany.com/?p=533</guid>
		<description><![CDATA[So I just hopped on the <a href="http://www.asp.net/mvc/" title="ASP.NET MVC Framework">ASP.NET MVC</a> bandwagon. As my first task, I undertook custom Action Filters for returning either JSON or XML as determined by the HTTP Request. Fortunately Omar AL Zabir did most of the work for creating a <a href="http://weblogs.asp.net/omarzabir/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx" title="MVC.NET JSON and XML Output">RESTful API</a> with ASP.NET MVC. The following is a filter which makes the whole thing much cleaner.]]></description>
			<content:encoded><![CDATA[<div class="toc">
<ol>
<li><a href="#toc-json-and-xml-action-filter-code">JSON and XML Action Filter Code</a></li>
<li><a href="#toc-usage-example">Usage Example</a></li>
<li><a href="#toc-sample-output">Sample Output</a></li>
</ol>
</div>
<p>So I just hopped on the <a href="http://www.asp.net/mvc/" title="ASP.NET MVC Framework">ASP.NET MVC</a> bandwagon. As my first task, I undertook custom Action Filters for returning either JSON or XML as determined by the HTTP Request. Fortunately Omar AL Zabir did most of the work for creating a <a href="http://weblogs.asp.net/omarzabir/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx" title="MVC.NET JSON and XML Output">RESTful API</a> with ASP.NET MVC.</p>
<h2 id="toc-json-and-xml-action-filter-code">JSON and XML Action Filter Code</h2>
<p>The following is a filter which makes the whole thing much cleaner. The filter looks for <code>Content-Type</code> headers in the HTTP request. If it matches <code>text/xml</code> then Plain Old XML (POX) is returned and if it matches <code>application/json</code> the output is JSON. This eliminates the need to write separate actions for JSON/XML and Views.</p>
<pre class="prettyprint">
using System;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Runtime.Serialization;
using System.Reflection;
using System.Reflection.Emit;

namespace AleemBawany.ActionFilters
{
  public class JsonPox : ActionFilterAttribute
  {
    private String[] _actionParams;

    // for deserialization
    public JsonPox(params String[] parameters)
    {
      this._actionParams = parameters;
    }

    // SERIALIZE
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
      if (!(filterContext.Result is ViewResult)) return;

      // SETUP
      UTF8Encoding utf8 = new UTF8Encoding(false);
      HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
      String contentType = request.ContentType ?? string.Empty;
      ViewResult view = (ViewResult)(filterContext.Result);
      var data = view.ViewData.Model;

      // JSON
      if (contentType.Contains("application/json") || request.IsAjaxRequest())
      {
        using (var stream = new MemoryStream())
        {
          JavaScriptSerializer js = new JavaScriptSerializer();

          String content = js.Serialize(data);
          filterContext.Result = new ContentResult
          {
            ContentType = "application/json",
            Content = content,
            ContentEncoding = utf8
          };
        }

      }

      // POX
      else if (contentType.Contains("text/xml"))
      {
        // MemoryStream to encapsulate as UTF-8 (default UTF-16)
        // http://stackoverflow.com/questions/427725/
        //
        // MemoryStream also used for atomicity but not here
        // http://stackoverflow.com/questions/486843/
        using (MemoryStream stream = new MemoryStream(500))
        {
          using (var xmlWriter =
            XmlTextWriter.Create(stream,
              new XmlWriterSettings()
              {
                OmitXmlDeclaration = true,
                Encoding = utf8,
                Indent = true
              }))
          {

            new DataContractSerializer(
              data.GetType(),
              null, // knownTypes
              65536, // maxItemsInObjectGraph
              false, // ignoreExtensionDataObject
              true, // preserveObjectReference - overcomes cyclical reference issues
              null // dataContractSurrogate
              ).WriteObject(stream, data);
          }

          filterContext.Result = new ContentResult
          {
            ContentType = "text/xml",
            Content = utf8.GetString(stream.ToArray()),
            ContentEncoding = utf8
          };
        }
      }
    }

    // DESERIALIZE
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

      if (_actionParams == null || _actionParams.Length == 0) return;

      HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
      String contentType = request.ContentType ?? string.Empty;
      Boolean isJson = contentType.Contains("application/json");

      if (!isJson) return;
      //@@todo Deserialize POX

      // JavascriptSerialier expects a single type to deserialize
      // so if the response contains multiple disparate objects to deserialize
      // we dynamically build a new wrapper class with fields representing those
      // object types, deserialize and then unwrap
      ParameterDescriptor[] paramDescriptors =
          filterContext.ActionDescriptor.GetParameters();
      Boolean complexType = paramDescriptors.Length > 1;

      Type wrapperClass;
      if (complexType)
      {
        Dictionary<String, Type> parameterInfo = new Dictionary<string, Type>();
        foreach (ParameterDescriptor p in paramDescriptors)
        {
          parameterInfo.Add(p.ParameterName, p.ParameterType);
        }
        wrapperClass = BuildWrapperClass(parameterInfo);
      }
      else
      {
        wrapperClass = paramDescriptors[0].ParameterType;
      }

      String json;
      using (var sr = new StreamReader(request.InputStream))
      {
        json = sr.ReadToEnd();
      }

      // then deserialize json as instance of dynamically created wrapper class
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      var result = typeof(JavaScriptSerializer)
              .GetMethod("Deserialize")
              .MakeGenericMethod(wrapperClass)
              .Invoke(serializer, new object[] { json });

      // then get fields from wrapper class assign the values back to the action params
      if (complexType)
      {
        for (Int32 i = 0; i < paramDescriptors.Length; i++)
        {
          ParameterDescriptor pd = paramDescriptors[i];
          filterContext.ActionParameters[pd.ParameterName] =
              wrapperClass.GetField(pd.ParameterName).GetValue(result);

        }
      }
      else
      {
        ParameterDescriptor pd = paramDescriptors[0];
        filterContext.ActionParameters[pd.ParameterName] = result;
      }
    }

    private Type BuildWrapperClass(Dictionary<string, Type> parameterInfo)
    {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "DynamicAssembly";
      AppDomain appDomain = AppDomain.CurrentDomain;
      AssemblyBuilder assemblyBuilder =
          appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder =
          assemblyBuilder.DefineDynamicModule("DynamicModule");
      TypeBuilder typeBuilder =
          moduleBuilder.DefineType("DynamicClass",
          TypeAttributes.Public | TypeAttributes.Class);

      foreach (KeyValuePair<String, Type> entry in parameterInfo)
      {
        String paramName = entry.Key;
        Type paramType = entry.Value;
        FieldBuilder field = typeBuilder.DefineField(paramName,
                    paramType, FieldAttributes.Public);
      }

      Type generatedType = typeBuilder.CreateType();
      // object generatedObject = Activator.CreateInstance(generatedType);

      return generatedType;
    }

  }
}
</pre>
<p>Last Updated: 28 March, 2010</p>
<h2 id="toc-usage-example">Usage Example</h2>
<p>To use this code in your Controller Action, you simply need to decorate it with the <code>[JsonPox]</code> attribute:</p>
<pre class="prettyprint">
// Depending on HTTP Content-Type header
// this returns JSON, XML or the default View

[JsonPox]
public ActionResult Index()
{
        ArrayList stuff = new ArrayList();
        stuff.Add("Hello World");
        stuff.Add(999);
        stuff.Add(1.0001);
        ViewData.Model = stuff;
        return View();
}
</pre>
<h2 id="toc-sample-output">Sample Output</h2>
<p>If <code>Content-Type: text/xml</code> HTTP header is present the output is:</p>
<pre class="prettyprint">
&lt;ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  &lt;anyType xsi:type="xsd:string"&gt;Hello World&lt;/anyType&gt;
  &lt;anyType xsi:type="xsd:int"&gt;999&lt;/anyType&gt;
  &lt;anyType xsi:type="xsd:double"&gt;1.0001&lt;/anyType&gt;
&lt;/ArrayOfAnyType&gt;
</pre>
<p>For the HTTP header <code>Content-Type: application/json</code> the output is:</p>
<pre class="prettyprint">
["Hello World",999,1.0001]
</pre>
<p>And if neither of those headers are present, the default View is returned.</p>
<p>Once again, if you intend to use it, get the latest bits for <a href="http://aleemb.svn.beanstalkapp.com/code/asp-net-mvc/JsonPoxFilter.cs">JsonPoxFilter.cs here</a> instead of copying the above code.</p>
]]></content:encoded>
			<wfw:commentRss>http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->