<?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>jesal gadhia &#187; J</title>
	<atom:link href="http://jesal.us/author/admin/feed/" rel="self" type="application/rss+xml" />
	<link>http://jesal.us</link>
	<description></description>
	<lastBuildDate>Thu, 14 Jul 2011 18:51:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Painless HABTM Validation in CakePHP</title>
		<link>http://jesal.us/2011/07/painless-habtm-validation-in-cakephp/</link>
		<comments>http://jesal.us/2011/07/painless-habtm-validation-in-cakephp/#comments</comments>
		<pubDate>Wed, 13 Jul 2011 08:00:19 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://jesal.us/?p=286</guid>
		<description><![CDATA[Recently I was faced with the task of validating a model with a HABTM relationship. I tried looking around for various solutions but all of them seemed quite complicated and time consuming to implement until I came across this nifty solution. Lets say you have two models &#8211; posts and tags with a HABTM relationship. [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was faced with the task of validating a model with a HABTM relationship. I tried looking around for various solutions but all of them seemed quite complicated and time consuming to implement until I came across <a href="http://bakery.cakephp.org/articles/kogalex/2010/01/13/quick-fix-for-habtm-validation" target="_blank">this nifty solution</a>. Lets say you have two models &#8211; posts and tags with a HABTM relationship.<br />
You probably already have the relationship defined in your model, if not, it goes something like this:</p>
<p><strong>models/post.php:</strong></p>
<pre>
var $hasAndBelongsToMany = array(
	'Tag' => array(
		'className' => 'Tag',
		'joinTable' => 'tags_posts',
		'foreignKey' => 'post_id',
		'associationForeignKey' => 'tag_id',
		'with' => 'TagsPost',
		'unique' => true,
		'conditions' => '',
		'fields' => '',
		'order' => '',
		'limit' => '',
		'offset' => '',
		'finderQuery' => '',
		'deleteQuery' => '',
		'insertQuery' => ''
	)
);
</pre>
<p>Now in addition to that, just go ahead and add multiple validation rule in your post model:</p>
<pre>
var $validate = array(
        'Tag' => array(
            'multiple' => array(
                'rule' => array('multiple',array('min' => 2)),
                'message' => 'Please select at least 2 tags'),
        ),
    );
</pre>
<p>And last but not least add a beforeValidate filter &#8230;</p>
<pre>
function beforeValidate() {
	foreach($this->hasAndBelongsToMany as $k=>$v) {
		if(isset($this->data[$k][$k]))
		{
			$this->data[$this->alias][$k] = $this->data[$k][$k];
		}
	}
}
</pre>
<p>All you have to do now is add the following snippet in your main model&#8217;s controller:</p>
<p><strong>controllers/posts_controller.php:</strong></p>
<pre>
&lt;?php
class PostsController extends Controller { 

    function beforeRender()
    {
        $model = Inflector::singularize($this-&gt;name);
        foreach($this-&gt;{$model}-&gt;hasAndBelongsToMany as $k=&gt;$v) {
            if(isset($this-&gt;{$model}-&gt;validationErrors[$k]))
            {
                $this-&gt;{$model}-&gt;{$k}-&gt;validationErrors[$k] = $this-&gt;{$model}-&gt;validationErrors[$k];
            }
        } 

    }
}
?&gt;
</pre>
<p>That will check for the errors raised in the main model&#8217;s validationErrors and copies them back to the HABTM&#8217;s model so that the view can correctly capture and print that validation error.</p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2011/07/painless-habtm-validation-in-cakephp/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Parse Twitter &amp; Facebook feeds with jQuery</title>
		<link>http://jesal.us/2011/01/parse-twitter-facebook-feeds-with-jquery/</link>
		<comments>http://jesal.us/2011/01/parse-twitter-facebook-feeds-with-jquery/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 22:29:26 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://jesal.us/?p=269</guid>
		<description><![CDATA[This post simply demonstrates how to parse Twitter and Facebook feeds using jQuery. I&#8217;m utilizing a JavaScript equivalent of C# prototype methods which I had talked about in one of my earlier posts. Also, you&#8217;ll note that I&#8217;m using two different date/time jQuery plugins to make Twitter and Facebook date parsing a little easier. One [...]]]></description>
			<content:encoded><![CDATA[<p>This post simply demonstrates how to parse Twitter and Facebook feeds using jQuery. I&#8217;m utilizing a JavaScript equivalent of C# prototype methods which I had talked about in one of my <a href="http://jesal.us/2009/05/how-to-parse-twitter-usernames-hashtags-and-urls-in-c-30/">earlier posts</a>. Also, you&#8217;ll note that I&#8217;m using two different date/time jQuery plugins to make Twitter and Facebook date parsing a little easier. One of them is <a href="http://timeago.yarp.com/">timeago</a> and the other one is <a href="http://blog.stevenlevithan.com/archives/date-time-format">dateFormat</a>. Although I had to put a condition to check if its IE as the dateFormat function was not playing nice with IE. Rest everything is pretty straight forward.</p>
<pre>
$(function () {
	$.ajax({
		url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jesalg&#038;trim_user=1&#038;count=5&#038;include_rts=1&#038;callback=?',
		dataType: 'json',
		success: displayTwitterFeed
	});
	$.ajax({
		url: 'https://graph.facebook.com/calistolabs/feed?limit=5&#038;access_token=XXXXXXXXXXXX|XXXXXXXXXXXXX|XXXXXXXXXXXXXXX&#038;callback=?', //Replace with your own access token
		dataType: 'json',
		success: displayFacebookFeed
	});
});

function displayTwitterFeed(result) {
	var outputTemplate = "&lt;p&gt;{0}&lt;br /&gt; &lt;small&gt;&lt;a href=\"{1}\"&gt;{2} via {3}&lt;/a&gt;&lt;/small&gt;&lt;/p&gt;";
	$.each(result, function (i, item) {
		var tweet = item.text.parseURL().parseUsername().parseHashtag();
		var createdAt = $.browser.msie ? item.created_at : $.timeago(dateFormat(item.created_at, "isoUtcDateTime"));
		var source = item.source;
		var tweetURL = "http://twitter.com/CalistoLabs/status/" + item.id_str;
		$("#TwitterFeed").append(outputTemplate.format(tweet, tweetURL, createdAt, source));
	});
}
function displayFacebookFeed(result) {
	var outputTemplate = "&lt;p&gt;&lt;strong&gt;&lt;a href=\"{0}\"&gt;{1}&lt;/a&gt;&lt;/strong&gt; {2}&lt;br /&gt;&lt;small&gt;{3}&lt;/small&gt;&lt;/p&gt;";
	$.each(result.data, function (i, item) {
		var username = item.from.name;
		var pageURL = "http://www.facebook.com/" + item.from.name.replace(/ /g, '');
		var date = $.browser.msie ? item.created_time : dateFormat(item.created_time.replace("+0000", ""), "dddd, mmmm dS, yyyy 'at' h:MM TT");
		var body = item.message;
		if (!body) {
			body = "&lt;a href='" + item.link + "'&gt;" + item.name + "&lt;/a&gt;&lt;br/&gt;" + item.description;
		}
		$("#FacebookFeed").append(outputTemplate.format(pageURL, username, body, date));
	});
}
String.prototype.parseURL = function () {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&#038;\?\/.=]+/g, function (url) {
		return url.link(url);
	});
};
String.prototype.parseUsername = function () {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function (u) {
		var username = u.replace("@", "")
		return u.link("http://twitter.com/" + username);
	});
};
String.prototype.parseHashtag = function () {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function (t) {
		var tag = t.replace("#", "%23")
		return t.link("http://search.twitter.com/search?q=" + tag);
	});
};
String.prototype.format = function () {
	var s = this,
        i = arguments.length;
	while (i--) {
		s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
	}
	return s;
};
</pre>
<p><strong>Edit:</strong></p>
<p>As of Friday June 3rd Facebook Graph API now requires a valid app or user access_token to access feed data: <a href="https://developers.facebook.com/blog/post/509/">https://developers.facebook.com/blog/post/509/</a> You can get your access_token from from the <a href="https://developers.facebook.com/tools/explorer/?method=GET&#038;path=calistolabs%2Ffeed%3Flimit%3D5%26callback%3D%3F">Graph API Explorer</a> and append it to your URL as a query string parameter as shown above.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2011/01/parse-twitter-facebook-feeds-with-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Cross-Domain Communication with IFrames</title>
		<link>http://jesal.us/2010/12/cross-domain-communication-with-iframes/</link>
		<comments>http://jesal.us/2010/12/cross-domain-communication-with-iframes/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 21:18:29 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://jesal.us/?p=259</guid>
		<description><![CDATA[Recently I encountered a situation where I had to communicate between an iframe located on a different domain and its parent. Due to the &#8220;same origin policy&#8221;, a security concept for browsers, which only permits scripts running on pages originating from the same site, this was not possible to do right out of the box. [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I encountered a situation where I had to communicate between an iframe located on a different domain and its parent. Due to the &#8220;same origin policy&#8221;, a security concept for browsers, which only permits scripts running on pages originating from the same site, this was not possible to do right out of the box. After some Googling, I learned there were a couple of workarounds for it. You could use dynamic script tags included from external domains aka JSONP or use postMessage or the IFrame URL technique. All of these solutions are quite hackish or complicated and not 100% secure. Luckily I found this nice little library called <a href="http://easyxdm.net/">easyXDM</a>.</p>
<blockquote><p>At the core easyXDM provides a transport stack capable of passing string based messages between two windows, a consumer (the main document) and a provider (a document included using an iframe). It does this by using one of several available techniques, always selecting the most efficient one for the current browser. For all implementations the transport stack offers bi-directionality, reliability, queueing and sender-verification.</p></blockquote>
<p>Here&#8217;s a small test I created. It calls a function to scroll the page up from the remote site. Local and remote directories represent the servers where the files will be residing on.</p>
<p><strong>local/methods.html</strong></p>
<pre>
&lt;!doctype html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;easyXDM&lt;/title&gt;
        &lt;script type="text/javascript" src="easyXDM.js"&gt;
        &lt;/script&gt;
        &lt;script type="text/javascript"&gt;
            var REMOTE = (function(){
                var remote = location.href;
                switch (location.host) {
                    case "jesal.us":
                        location.href = remote.replace("provider", "consumer");
                        break;
                    case "calistolabs.com":
                        remote = remote.replace("calistolabs.com", "jesal.us");
                        break;
                }
                return remote.substring(0, remote.lastIndexOf("/"));
            }());
            var remote = new easyXDM.Rpc(/** The channel configuration */{
                /**
                 * Register the url to hash.html, this must be an absolute path
                 * or a path relative to the root.
                 * @field
                 */
                local: "name.html",
                /**
                 * Register the url to the remote interface
                 * @field
                 */
                remote: REMOTE + "/../remote/remotemethods.html",
                remoteHelper: REMOTE + "/../remote/name.html",
                /**
                 * Register the DOMElement that the generated IFrame should be inserted into
                 */
                container: "embedded",
                props: {
                    style: {
                        border: "2px dotted red",
                        height: "1200px"
                    }
                }
            }, /** The interface configuration */ {
                local: {
                    triggerScrollUp: function(){
						scroll(0,0);
                    }
                }
            });
        &lt;/script&gt;
        &lt;style type="text/css"&gt;
            #embedded iframe {
                width: 100%;
                height: 100%;
            }
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;script type="text/javascript"&gt;
            document.write("Domain: " + location.host);
        &lt;/script&gt;
            &lt;br/&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;br&gt;
			&lt;div id="embedded"&gt;
			&lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>remote/remotemethods.html</strong></p>
<pre>
&lt;!doctype html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;easyXDM&lt;/title&gt;
        &lt;script type="text/javascript" src="easyXDM.js"&gt;
        &lt;/script&gt;
        &lt;script type="text/javascript"&gt;
            var remote = new easyXDM.Rpc(/** The channel configuration*/{
                local: "name.html",
				onReady: function(){
                    /**
                     * Call a method on the other side
                     */
                    remote.triggerScrollUp();
                }
            }, /** The configuration */ {
                remote: {
                    triggerScrollUp: {}
                }
            });
        &lt;/script&gt;
    &lt;/head&gt;

    &lt;body&gt;
        &lt;script type="text/javascript"&gt;
            document.write("Domain: " + location.host);
        &lt;/script&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;br&gt;
		&lt;input type="button" onclick="remote.triggerScrollUp();" value="Call to triggerScrollUp on mother ship"/&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>remote/name.html</strong></p>
<pre>
&lt;!doctype html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;&lt;/title&gt;
        &lt;meta http-equiv="CACHE-CONTROL" content="PUBLIC"/&gt;
        &lt;meta http-equiv="EXPIRES" content="Sat, 01 Jan 2050 00:00:00 GMT"/&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;script type="text/javascript"&gt;

        function sendMessage(message, url){
            window.setTimeout(function(){
                window.name = message;
                location.href = url + "," + encodeURIComponent(location.protocol + "//" + location.host + location.pathname);
            }, 0);
        }

        if (location.hash) {
            if (location.hash.substring(1, 2) === "_") {
                var channel, url, hash = location.href.substring(location.href.indexOf("#") + 3), indexOf = hash.indexOf(",");
                if (indexOf == -1) {
                    channel = hash;
                }
                else {
                    channel = hash.substring(0, indexOf);
                    url = decodeURIComponent(hash.substring(indexOf + 1));
                }
                switch (location.hash.substring(2, 3)) {
                    case "2":
                        // NameTransport local
                        window.parent.parent.easyXDM.Fn.get(channel)(window.name);
                        location.href = url + "#_4" + channel + ",";
                        break;
                    case "3":
                        // NameTransport remote
                        var guest = window.parent.frames["easyXDM_" + channel + "_provider"];
                        if (!guest) {
                            throw new Error("unable to reference window");
                        }
                        guest.easyXDM.Fn.get(channel)(window.name);
                        location.href = url + "#_4" + channel + ",";
                        break;
                    case "4":
                        // NameTransport idle
                        var fn = window.parent.easyXDM.Fn.get(channel + "_load");
                        if (fn) {
                            fn();
                        }
                        break;
                }
            }
        }
        &lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>You can find lot more examples and documentation on easyXDM&#8217;s <a href="http://easyxdm.net/wp/category/examples/">website</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2010/12/cross-domain-communication-with-iframes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Integrating CodeIgniter with WordPress</title>
		<link>http://jesal.us/2010/12/integrating-codeigniter-with-wordpress/</link>
		<comments>http://jesal.us/2010/12/integrating-codeigniter-with-wordpress/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 20:13:58 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[codeigniter]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://jesal.us/?p=242</guid>
		<description><![CDATA[Recently I was working on a website for a small business client. They wanted a simple system to allow them to easily update a section of their website. Since it was a small website, I wanted to accomplish this without putting too much time but still creating something user-friendly and easy to use that can [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I was working on a website for a small business client. They wanted a simple system to allow them to easily update a section of their website. Since it was a small website, I wanted to accomplish this without putting too much time but still creating something user-friendly and easy to use that can get the job done. The main site was made using CodeIgniter. So we decided to create a WordPress blog for the client where they could put their content and I would pull that content inside their CI website. Here&#8217;s how:</p>
<p>First of all, install WordPress in a folder called blog in your website. It would be located at the top level directory of the website. So it would be alongside the system folder of the CI installation. If you already have a DB for your site, have WordPress add tables to that same DB with a prefix to make things simple (although this is not a requirement).</p>
<p>Once that&#8217;s done. All you have to do is add the following line in the at the top of your CodeIgniter&#8217;s index.php file. Change the path to wp-blog-header.php as needed to point to your wordpress&#8217;s root directory.</p>
<pre>
&lt;?php
require('blog/wp-blog-header.php');
</pre>
<p>One you get that dialed in, rest is pretty straight forward. All of WordPress&#8217; native API functions should now be accessible to you. So you could throw in a WordPress loop in any of the CI views like for example:</p>
<p><b>Articles.php (View):</b></p>
<pre>
&lt;?php
if ($type == 'Tag') { query_posts('tag='.$id.'&#038;posts_per_page=-1'); }
else if ($type == 'Category') { query_posts('category_name='.$id.'&#038;posts_per_page=-1'); }
else { query_posts('posts_per_page=-1'); }
while (have_posts()) : the_post(); // Loop
?&gt;
	&lt;a href="&lt;?=base_url();?&gt;Research/Article/&lt;?php the_ID(); ?&gt;"&gt;&lt;h4&gt;&lt;?php the_title(); ?&gt;&lt;/h4&gt;&lt;/a&gt;
	By &lt;?php the_author(); ?&gt;
	&lt;p class="details"&gt;&lt;? the_time('F jS, Y') ?&gt;&lt;/p&gt;
	&lt;?php the_excerpt(); ?&gt;
	&lt;hr/&gt;
&lt;?php
	endwhile; // End Loop
?&gt;
</pre>
<p>&#8230;and a sidebar on the same which which would list out all the tags and categories to select from:</p>
<pre>
&lt;!-- SIDE BAR --&gt;
&lt;div id="sideBar"&gt;
	&lt;h3&gt;Categories:&lt;/h3&gt;
	&lt;?php
	$args = array(
	'show_option_all'    =&gt; '',
	'orderby'            =&gt; 'name',
	'order'              =&gt; 'ASC',
	'show_last_update'   =&gt; '0',
	'style'              =&gt; 'none',
	'show_count'         =&gt; '0',
	'hide_empty'         =&gt; '1',
	'use_desc_for_title' =&gt; '1',
	'child_of'           =&gt; '0',
	'feed'               =&gt; '',
	'feed_type'          =&gt; '',
	'feed_image'         =&gt; '',
	'exclude'            =&gt; '',
	'exclude_tree'       =&gt; '',
	'include'            =&gt; '',
	'current_category'   =&gt; '0',
	'hierarchical'       =&gt; 'true',
	'title_li'           =&gt; __( 'Categories' ),
	'number'             =&gt; NULL,
	'echo'               =&gt; '1',
	'depth'              =&gt; '0');
	wp_list_categories( $args ); ?&gt;
	&lt;br&gt;

	&lt;h3&gt;Tags:&lt;/h3&gt;
	&lt;?php
	$args = array(
	'smallest'  =&gt; '12',
	'largest'   =&gt; '12',
	'unit'      =&gt; 'px',
	'number'    =&gt; '45',
	'format'    =&gt; 'flat',
	'separator' =&gt; ' ',
	'orderby'   =&gt; 'name',
	'order'     =&gt; 'ASC',
	'exclude'   =&gt; '',
	'include'   =&gt; '',
	'link'      =&gt; 'custom',
	'taxonomy'  =&gt; 'post_tag',
	'echo'      =&gt; true,
	'link_url'  =&gt; base_url()."Research/Articles/Tag/");
	wp_tag_cloud( $args ); ?&gt;

&lt;/div&gt;
&lt;!-- /SIDE BAR --&gt;
</pre>
<p><b>Article.php (View):</b></p>
<pre>
&lt;!-- CONTENT --&gt;
&lt;div id="mainContent"&gt;

    &lt;!-- LEFT NAV --&gt;
    &lt;div id="leftNav"&gt;
        &lt;a href="&lt;?=base_url();?&gt;Research/Articles" class="selected"&gt;Articles&lt;/a&gt;
    &lt;/div&gt;
    &lt;!-- /LEFT NAV --&gt;

    &lt;!-- MAIN COL --&gt;
    &lt;div id="mainColWide"&gt;
        &lt;h1&gt;&lt;?= $post-&gt;post_title ?&gt;&lt;/h1&gt;
        &lt;p class="details"&gt;&lt;?= the_time('F j, Y') ?&gt;&lt;/p&gt;
        &lt;?= wpautop($post-&gt;post_content) ?&gt;
        &lt;br/&gt;&lt;br/&gt;
        &lt;a href="&lt;?=base_url();?&gt;Research/Articles"&gt;back&lt;/a&gt;
    &lt;/div&gt;
    &lt;!-- /MAIN COL --&gt;
    &lt;br class="clearFloat" /&gt;
&lt;/div&gt;
&lt;!-- /CONTENT --&gt;
</pre>
<p><b>Research.php (Controller):</b></p>
<pre>
&lt;?php

class Research extends Base_Controller {

	function Research()
	{
        parent::Base_Controller();
	}

	function Index()
	{
        $this-&gt;data['content'] = $this-&gt;load-&gt;view('Research/index.php', $this-&gt;data, true);
        $this-&gt;load-&gt;view('layouts/master' ,$this-&gt;data);
	}

    function Articles($type = '', $id = '')
	{
        $this-&gt;data['type'] = $type;
        $this-&gt;data['id'] = $id;
        $this-&gt;data['content'] = $this-&gt;load-&gt;view('Research/articles.php', $this-&gt;data, true);
        $this-&gt;load-&gt;view('layouts/master' ,$this-&gt;data);
	}

    function Article($id)
	{
        $this-&gt;data['post'] = get_post($id);
        $this-&gt;data['id'] = $id;
        $this-&gt;data['content'] = $this-&gt;load-&gt;view('Research/article.php', $this-&gt;data, true);
        $this-&gt;load-&gt;view('layouts/master' ,$this-&gt;data);
	}
}
</pre>
<p>That&#8217;s it! This would allow us to browse all the blog entries without leaving the CI site. Other helper functions can also be found in WordPress&#8217;s documentation which can assist you in integrating the design.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2010/12/integrating-codeigniter-with-wordpress/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to parse WordPress RSS feed using LINQ</title>
		<link>http://jesal.us/2010/03/how-to-parse-wordpress-rss-feed-using-linq/</link>
		<comments>http://jesal.us/2010/03/how-to-parse-wordpress-rss-feed-using-linq/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 05:32:28 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://jesal.us/?p=238</guid>
		<description><![CDATA[Here&#8217;s a code snippet of parsing a typical WordPress RSS feed using LINQ. Note, we have to skip the first image from the media element since that&#8217;s usually a gravatar of the author. Everything else is pretty straight forward. private void BindBlogFeed() { XDocument doc = XDocument.Load("http://blogworkseverytime.wordpress.com/feed/"); XNamespace content = "http://purl.org/rss/1.0/modules/content/"; XNamespace media = "http://search.yahoo.com/mrss/"; [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a code snippet of parsing a typical WordPress RSS feed using LINQ. Note, we have to skip the first image from the media element since that&#8217;s usually a gravatar of the author.</p>
<p>Everything else is pretty straight forward.</p>
<pre>
    private void BindBlogFeed()
    {
        XDocument doc = XDocument.Load("http://blogworkseverytime.wordpress.com/feed/");
        XNamespace content = "http://purl.org/rss/1.0/modules/content/";
        XNamespace media = "http://search.yahoo.com/mrss/";

        var query = (from feed in doc.Descendants("item")
                     orderby DateTime.Parse(feed.Element("pubDate").Value) descending
                     select new
                     {
                         Title = feed.Element("title").Value,
                         Description = HttpUtility.HtmlDecode(feed.Element("description").Value),
                         Content = HttpUtility.HtmlDecode(feed.Element(content.GetName("encoded")).Value),
                         Image = (from img in feed.Elements(media.GetName("content"))
                                  where img.Attribute("url").Value.Contains("gravatar") == false
                                  select img.Attribute("url").Value).FirstOrDefault() ?? "",
                         Link = feed.Element("link").Value,
                         Date = DateTime.Parse(feed.Element("pubDate").Value).ToShortDateString()
                     });

        lvFirstBlogFeed.DataSource = query.Take(1).ToList();
        lvFirstBlogFeed.DataBind();

        lvRemainingBlogFeed.DataSource = query.Skip(1).ToList();
        lvRemainingBlogFeed.DataBind();
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2010/03/how-to-parse-wordpress-rss-feed-using-linq/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>CodeIgniter + Facebook Connect</title>
		<link>http://jesal.us/2010/01/codeigniter-facebook-connect/</link>
		<comments>http://jesal.us/2010/01/codeigniter-facebook-connect/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 20:11:41 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[codeigniter]]></category>
		<category><![CDATA[facebook]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://jesal.us/?p=183</guid>
		<description><![CDATA[In this post I will talk about how to create a Facebook Connect site using the CodeIgniter framework. So first of all, before you being, download the Facebook Platform client library from here. Extract the files and copy everything inside /php folder (including the &#8216;jsonwrapper&#8217; folder) to the /system/plugins folder of your CI application. Once [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I will talk about how to create a Facebook Connect site using the CodeIgniter framework. </p>
<p>So first of all, before you being, download the Facebook Platform client library from <a href="http://wiki.developers.facebook.com/index.php/PHP" target="_blank">here</a>. Extract the files and copy everything inside /php folder (including the &#8216;jsonwrapper&#8217; folder) to the <strong>/system/plugins</strong> folder of your CI application. Once you do that, rename the <strong>facebook.php file to facebook_pi.php</strong>. Doing so will make CI recognize the library as a plugin. Now you will be able to reference the library just how you would reference any other plugins as you will see below.</p>
<p>Once you&#8217;ve done that. We are all set to write some code. The first key step to this is to extend the base controller and create a Facebook Controller that can handle user authentication and pass other needed variables. This extended controller would have to reside in <strong>/system/application/libraries/MY_Controller.php</strong>:</p>
<pre>
class Facebook_Controller extends Controller {

    var $facebook;
    var $fb_uid;
    var $fb_user_details;
    var $user;
    var $permissions_to_request;
    var $logged_in;

    public $data;

	function Facebook_Controller() {

	parent::Controller();

        $this->output->set_header("Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        $this->output->set_header("Pragma: no-cache");

        // Created some Facebook helper functions to make things easier and pull API Key, Secret Key, Base URLs, etc from the Facebook config file.
        $this->__fbApiKey = get_facebook_api_key();
        $this->__fbSecret = get_facebook_secret_key();

        // Prevent the 'Undefined index: facebook_config' notice from being thrown.
        $GLOBALS['facebook_config']['debug'] = NULL;

        // Create a Facebook client API object.
        $this->facebook = new Facebook($this->__fbApiKey, $this->__fbSecret);
        $this->fb_uid = $this->facebook->get_loggedin_user();

        //Check to see if the user is logged in with facebook
        if($this->fb_uid)
        {
            $fb_uid = $this->fb_uid;

            //If this is the first login with the site
            if(!$this->_get_user_session_object($fb_uid))
            {
                //Check to see if user is in the db
                $this->load->model('User_model');
                $this->user = $this->User_model->get_user_by_fb_uid($fb_uid);
                $this->fb_user_details = $this->Facebook_model->get_user_details($fb_uid);

                //If its not in the db, do an insert
                if(!$this->user)
                {
                   $user_data = array('fb_uid' => $fb_uid, 'created_at' => date('Y-m-d H:i:s'));
                   $user_id = $this->User_model->insert_user($user_data);

				   //Give them a default username
                   $user_data = array('username' => 'user'.$user_id);
				   $this->User_model->update_user($user_id, $user_data);

                    $this->user = $this->User_model->get_user_by_user_id($user_id);
                }

                $this->_set_user_session_object($fb_uid, $this->user);
                $this->_set_user_details_session_object($fb_uid, $this->fb_user_details);

                //Check to see if user has all the required permissions
                $has_publish_stream_permission = $this->facebook->api_client->call_method('Users.hasAppPermission',array('ext_perm'=>'publish_stream', 'uid'=>$fb_uid));
                $has_email_permission = $this->facebook->api_client->call_method('Users.hasAppPermission',array('ext_perm'=>'email', 'uid'=>$fb_uid));

                //Request the missing permissions
                $permissions_to_request = $has_publish_stream_permission == 0 ? "publish_stream" : null;
                if($permissions_to_request)
                    $permissions_to_request .= ",";
                $permissions_to_request .= $has_email_permission == 0 ? "email" : null;

                // I wanted to use this approach but it left a trailing comma in the end so it didn't work out. I'm sure there is a way around it.
                //$arry_permissions_to_request = array($has_publish_stream_permission == 0 ? "publish_stream" : null, $has_email_permission == 0 ? ",email" : null);
                //$permissions_to_request = implode(",", $arry_permissions_to_request);

                $this->permissions_to_request = $permissions_to_request;
            }
            else
            {
                //Load the user object back from the session
                $this->user = $this->_get_user_session_object($this->fb_uid);
                $this->fb_user_details = $this->_get_user_details_session_object($this->fb_uid);
            }
        }

        //Set master page data variables
        $this->data['user'] = $this->user;
        $this->data['fb_user_details'] = $this->fb_user_details;
        $this->logged_in = ($this->user &#038;&#038; $this->fb_uid)? true : false;
        $this->data['logged_in'] = $this->logged_in;
        $this->data['request_permissions'] = $this->permissions_to_request ? true : false;
        $this->data['permissions_to_request'] = $this->permissions_to_request;
        $this->data['fb_login_prompt'] = false;
        $this->data['current_controller'] = get_class($this);
	}

    function _get_user_session_object($fb_uid)
    {
        return $this->session->userdata($fb_uid.'_user_object');
    }

    function _get_user_details_session_object($fb_uid)
    {
        return $this->session->userdata($fb_uid.'_user_details_object');
    }

    function _set_user_session_object($fb_uid, $user)
    {
        $this->session->set_userdata($fb_uid.'_user_object', $user);
    }

    function _set_user_details_session_object($fb_uid, $fb_user_details)
    {
        $this->session->set_userdata($fb_uid.'_user_details_object', $fb_user_details);
    }
}
</pre>
<p>Once we have that setup, we can go ahead and create a master page which will load the header, footer, navigation and all the other site-wide global elements. Part of which, the header, could look something like this, it would show the user&#8217;s profile pic &#038; name when logged in and show a Facebook Connect button when logged out. You can put this master page inside <strong>/system/application/views/layouts/master.php</strong>:</p>
<pre>
&lt;div id="header"&gt;
&lt;?php if (!$logged_in) { ?&gt;
&lt;div style="margin-top:18px"&gt;
	&lt;a href="#" id="fbconnect_login_button" class="fbconnect_login_button" onclick="FB.Connect.requireSession(); return false;" &gt;
		&lt;img id="fb_login_image" src="http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_medium_long.gif" style="border:0;" alt="Connect"/&gt;
	&lt;/a&gt;
&lt;/div&gt;
&lt;?php } else { ?&gt;
	&lt;div class="floatR"&gt;
		&lt;fb:profile-pic uid="&lt;?=$user['fb_uid']?&gt;" size="square" facebook-logo="true"&gt;&lt;/fb:profile-pic&gt;
	&lt;/div&gt;
	&lt;div class="floatR" style="margin-top:13px"&gt;
	Welcome, &lt;?=$fb_user_details[0]['name']?&gt;
	&lt;br /&gt;
	&lt;a href="#" onclick="FB.Connect.logout(function() { facebook_onlogout(); }); facebook_onlogout()"&gt;Logout of Facebook&lt;/a&gt;
	&lt;/div&gt;
	&lt;br class="clearFloat" /&gt;
&lt;?php } ?&gt;
&lt;/div&gt;
</pre>
<p>Content area would just be one variable which will load the content from the page controller as we will see further on:</p>
<pre>
&lt;div id="mainContent"&gt;
	&lt;?=$content?&gt;
&lt;/div&gt;
</pre>
<p>And finally, the most important part, the footer which would load &#038; initialize the Facebook library, take care of prompting for the right permissions, and require the user to login on certain pages based on the controller:</p>
<pre>
&lt;div id="footer"&gt;
	&lt;script type="text/javascript"&gt;
		function setFocus() { window.document.&lt;?=$current_controller?&gt;.focus(); }
	&lt;/script&gt;
	&lt;script src="&lt;?=get_static_facebook_root();?&gt;/js/api_lib/v0.4/FeatureLoader.js.php/en_US" type="text/javascript"&gt;&lt;/script&gt;
	&lt;script type="text/javascript"&gt;
		FB.init("&lt;?=get_facebook_api_key();?&gt;", "&lt;?=base_url();?&gt;xd_receiver.htm", {"reloadIfSessionStateChanged":true});
	&lt;/script&gt;
	&lt;script src="&lt;?=base_url();?&gt;shared/js/fbconnect.js" type="text/javascript"&gt;&lt;/script&gt;
	&lt;script type="text/javascript"&gt;
		window.onload = function() {
			facebook_onload(&lt;?=$logged_in?&gt;);
			&lt;?php if ($request_permissions) { ?&gt;facebook_prompt_permission("&lt;?=$permissions_to_request?&gt;");&lt;?php } ?&gt;
		};
	&lt;/script&gt;
	&lt;?php if ($fb_login_prompt &#038;&#038; !$logged_in) { ?&gt;
	&lt;script type="text/javascript"&gt;
		FB.ensureInit(function() {
			FB.Connect.requireSession(null, function(){ location.href = "&lt;?=base_url();?&gt;home"; });
		});
	&lt;/script&gt;
	&lt;?php } ?&gt;
&lt;/div&gt;
</pre>
<p>As you can see, I&#8217;ve used some JavaScript in fbconnect.js to help us invoke the permissions and/or dialog box as needed:</p>
<pre>
/*
 * The facebook_onload statement is printed out in the PHP. If the user's logged in
 * status has changed since the last page load, then refresh the page to pick up
 * the change.
 *
 * This helps enforce the concept of "single sign on", so that if a user is signed into
 * Facebook when they visit your site, they will be automatically logged in -
 * without any need to click the login button.
 *
 * @param already_logged_into_facebook  reports whether the server thinks the user
 *                                      is logged in, based on their cookies
 *
 */
function facebook_onload(already_logged_into_facebook) {
  // user state is either: has a session, or does not.
  // if the state has changed, detect that and reload.
  FB.ensureInit(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function(session) {
          var is_now_logged_into_facebook = session ? true : false;

          // if the new state is the same as the old (i.e., nothing changed)
          // then do nothing
          if (is_now_logged_into_facebook == already_logged_into_facebook) {
            return;
          }

          // otherwise, refresh to pick up the state change
          refresh_page();
        });
    });
}

function facebook_onlogin_ready() {
  refresh_page();
}

function facebook_onlogout() {
    $.post("./Logout", null, null);
}

function refresh_page() {
    location.reload(true);
}

function facebook_prompt_permission(permission) {
  FB.ensureInit(function() {
    FB.Connect.showPermissionDialog(permission);
  });
}
</pre>
<p>Now that we have the master page setup, we can inject our content into the master page from any page controller:</p>
<pre>
class Test extends Facebook_Controller {

   function Test()
   {
        parent::Facebook_Controller();
   }

   function Index()
   {
        $this->data['fb_login_prompt'] = true;
        $this->data['content'] = $this->load->view('test', $this->data, true);
        $this->load->view('layouts/master' ,$this->data);
   }
</pre>
<p>So, thats it! Now you should have a fully functional Facebook connect site in CodeIgniter!</p>
<p>Inspired by:<br />
<a href="http://junal.wordpress.com/2008/01/20/a-sample-facebook-application-with-codeigniter/" target="_blank">http://junal.wordpress.com/2008/01/20/a-sample-facebook-application-with-codeigniter/</a><br />
<a href="http://www.simpleprojectz.com/2008/10/facebook-codeigniter/" target="_blank">http://www.simpleprojectz.com/2008/10/facebook-codeigniter/</a><br />
<a href="http://codeigniter.com/forums/viewthread/120393/" target="_blank">http://codeigniter.com/forums/viewthread/120393/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2010/01/codeigniter-facebook-connect/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>How To Setup Pretty Premalinks for WordPress on IIS7</title>
		<link>http://jesal.us/2009/06/pretty-premalinks-for-wordpress-on-iis7/</link>
		<comments>http://jesal.us/2009/06/pretty-premalinks-for-wordpress-on-iis7/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 02:58:36 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[iis]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=152</guid>
		<description><![CDATA[If you&#8217;re running WordPress on IIS7 like this blog and if you want clean URLs without the &#8220;index.php&#8221; you can do the following. Although before you get started you need to make sure you have FastCGI and URL Rewrite Module installed on your IIS7. If you&#8217;re missing one of those things, you can check out [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re running WordPress on IIS7 like this blog and if you want clean URLs without the &#8220;index.php&#8221; you can do the following. </p>
<p>Although before you get started you need to make sure you have FastCGI and URL Rewrite Module installed on your IIS7.</p>
<p>If you&#8217;re missing one of those things, you can check out these guides:</p>
<p>- <a href="http://learn.iis.net/page.aspx/460/using-url-rewrite-module/" target="_blank">Using URL Rewrite Module</a><br />
- <a href="http://learn.iis.net/page.aspx/375/setting-up-fastcgi-for-php/" target="_blank">Setting up FastCGI for PHP</a></p>
<p>Once you&#8217;ve done that, go to the &#8220;Settings&#8221; section in your WordPress admin area and click on &#8220;Premalinks&#8221;:</p>
<p><img src="http://jesal.us/wp-content/uploads/premalinks-1024x524.jpg" alt="premalinks" title="premalinks"/></p>
<p>On that page, choose the &#8220;Custom, specify below&#8221; option and enter<br />
&#8220;/%year%/%monthnum%/%postname%/&#8221; (or any other format of your choosing) in the &#8220;Custom structure&#8221; text box.</p>
<p>After you save the settings, you&#8217;ll notice that all your blog posts will have their URLs in the format you specified earlier. Although if you try to click on one of them you&#8217;ll get a 404 &#8211; File Not Found error. Thats because we still haven&#8217;t told the server where to go when it gets those requests. </p>
<p>To do so, you&#8217;ll have to create a Web.Config file (if you don&#8217;t have one already) in the same directory as your WordPress blog. Once you&#8217;ve done that, paste the following inside configuration->system.webServer element:</p>
<pre>
&lt;rewrite&gt;
    &lt;rules&gt;
        &lt;rule name="Main Rule" stopProcessing="true"&gt;
            &lt;match url=".*" /&gt;
            &lt;conditions logicalGrouping="MatchAll"&gt;
                &lt;add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /&gt;
                &lt;add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /&gt;
            &lt;/conditions&gt;
            &lt;action type="Rewrite" url="index.php" /&gt;
        &lt;/rule&gt;
    &lt;/rules&gt;
&lt;/rewrite&gt;
</pre>
<p><a href="http://jesal.us/wp-content/uploads/web.config.txt" target="_blank">Click here</a> to download the entire Web.Config file.</p>
<p>That rewrite rule we added above will match any requested URL and if that URL does not corresponds to a file or a folder on a file system, then it will rewrite the URL to Index.php. At that point, WordPress will determine which content to serve based on the REQUEST_URI server variable that contains the original URL before it was modified by the rule.</p>
<p>After you&#8217;ve saved the Web.config file, fire up any one of the permalinks in your WordPress blog. If everything went as expected, you&#8217;ll see the correct content returned by the web server for every permalink.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2009/06/pretty-premalinks-for-wordpress-on-iis7/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>How to Parse Twitter Usernames, Hashtags and URLs in C# 3.0</title>
		<link>http://jesal.us/2009/05/how-to-parse-twitter-usernames-hashtags-and-urls-in-c-30/</link>
		<comments>http://jesal.us/2009/05/how-to-parse-twitter-usernames-hashtags-and-urls-in-c-30/#comments</comments>
		<pubDate>Wed, 06 May 2009 22:13:27 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=132</guid>
		<description><![CDATA[Lately I&#8217;ve been working on my pet project called Twime. So as part of that project, I wanted to add the ability to parse URLs, usernames and hashtags from the user&#8217;s Twitter timeline. Here&#8217;s how I went about doing that: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text.RegularExpressions; public static class HTMLParser { [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been working on my pet project called <a href="http://jesal.us/twime/" target="_blank">Twime</a>. So as part of that project, I wanted to add the ability to parse URLs, usernames and hashtags from the user&#8217;s Twitter timeline. Here&#8217;s how I went about doing that:</p>
<pre name="code" class="c-sharp:nogutter;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

public static class HTMLParser
{
    public static string Link(this string s, string url)
    {
        return string.Format("&lt;a href=\"{0}\" target=\"_blank\"&gt;{1}&lt;/a&gt;", url, s);
    }
    public static string ParseURL(this string s)
    {
        return Regex.Replace(s, @"(http(s)?://)?([\w-]+\.)+[\w-]+(/\S\w[\w- ;,./?%&#038;=]\S*)?", new MatchEvaluator(HTMLParser.URL));
    }
    public static string ParseUsername(this string s)
    {
        return Regex.Replace(s, "(@)((?:[A-Za-z0-9-_]*))", new MatchEvaluator(HTMLParser.Username));
    }
    public static string ParseHashtag(this string s)
    {
        return Regex.Replace(s, "(#)((?:[A-Za-z0-9-_]*))", new MatchEvaluator(HTMLParser.Hashtag));
    }
    private static string Hashtag(Match m)
    {
        string x = m.ToString();
        string tag = x.Replace("#", "%23");
        return x.Link("http://search.twitter.com/search?q=" + tag);
    }
    private static string Username(Match m)
    {
        string x = m.ToString();
        string username = x.Replace("@", "");
        return x.Link("http://twitter.com/" + username);
    }
    private static string URL(Match m)
    {
        string x = m.ToString();
        return x.Link(x);
    }
}
</pre>
<p>So as you can see I&#8217;m using the new <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx" target="_blank">Extension Methods</a> feature in C# 3.0.</p>
<p>Now I can simply just call the extension methods like this:</p>
<pre name="code" class="c-sharp:nogutter;">
string tweet = "Just blogged about how to parse HTML from the @twitter timeline - http://jesal.us/blog/?p=132 #programming";
Response.Write(tweet.ParseURL().ParseUsername().ParseHashtag());
</pre>
<p>and the result should looks something like this:</p>
<p>Just blogged about how to parse html from the <a href="http://twitter.com/twitter" target="_blank">@twitter</a> timeline &#8211; <a href="http://jesal.us/blog/?p=132" target="_blank">http://jesal.us/blog/?p=132</a> <a href="http://search.twitter.com/search?q=%23programming">#programming</a></p>
<p>Just be sure to call ParseURL method before ParseUsername and ParseHashtag. The other two methods will add URLs to the usernames and hastags and you don&#8217;t want ParseURL to confuse those links with the original links present in the text.</p>
<p>This was inspired by <a href="http://www.simonwhatley.co.uk/" target="_blank">Simon Whatley</a>&#8216;s <a href="http://www.simonwhatley.co.uk/parsing-twitter-usernames-hashtags-and-urls-with-javascript" target="_blank">post</a> about doing something similar using prototyping with JavaScript.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2009/05/how-to-parse-twitter-usernames-hashtags-and-urls-in-c-30/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Calculate Shipping Cost Using UPS OnLine Tools</title>
		<link>http://jesal.us/2009/02/calculate-shipping-cost-using-ups-webservice/</link>
		<comments>http://jesal.us/2009/02/calculate-shipping-cost-using-ups-webservice/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 05:46:39 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[shipping]]></category>
		<category><![CDATA[ups]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=101</guid>
		<description><![CDATA[Before using this code, all you need to do is register for an UPS OnLine Tools account and then apply for a XML Access key using your developer key which you will receive after creating an account. After you get your access key, just plug your username, password and the key into the highlighted line [...]]]></description>
			<content:encoded><![CDATA[<p>Before using this code, all you need to do is <a href="https://www.ups.com/one-to-one/register" target="_blank">register for an UPS OnLine Tools account</a> and then apply for a <a href="https://www.ups.com/e_comm_access/laServ?START_PAGE=INTRO&#038;CURRENT_PAGE=GET_ACCESS_KEY&#038;OPTION=ACCESS_LIC_XML&#038;loc=en_US" target="_blank">XML Access key</a> using your developer key which you will receive after creating an account. After you get your access key, just plug your username, password and the key into the highlighted line below and you should be good to go!</p>
<pre name="code" class="c-sharp:nogutter;highlight:[32]">
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;

///
<summary>
/// Summary description for ShippingCalculator
/// </summary>

namespace ad2.BusinessLogic
{
    public static class ShippingCalculator
    {
        public static decimal GetShippingCost(string shipFromZipCode, string shipToZipCode, string serviceRateCode, string packageWeight)
        {
            decimal shippingCost = -1;
            string URL = "https://www.ups.com/ups.app/xml/Rate";
            WebRequest objRequest = WebRequest.Create(URL);
            objRequest.Method = "POST";
            objRequest.ContentType = "application/x-www-form-urlencoded";

            using (StreamWriter writer = new StreamWriter(objRequest.GetRequestStream()))
            {
                writer.Write(GetAuthXML("accesskey", "username", "password"));
                writer.Write(GetRequestXML(shipFromZipCode, shipToZipCode, serviceRateCode, packageWeight));
                writer.Flush();
                writer.Close();
            }

            objRequest.Timeout = 5000;

            try
            {
                using (WebResponse objResponse = objRequest.GetResponse())
                {
                    XmlDocument xmlResponse = new XmlDocument();
                    xmlResponse.Load(objResponse.GetResponseStream());
                    int responseStatusCode = int.Parse(xmlResponse.SelectSingleNode("//RatingServiceSelectionResponse/Response/ResponseStatusCode").InnerText);

                    if (responseStatusCode == 1)
                    {
                        XmlNodeList xmlNodeList = xmlResponse.SelectNodes(string.Format("/RatingServiceSelectionResponse/RatedShipment/TotalCharges[../Service/Code={0}]/MonetaryValue", serviceRateCode));

                        foreach (XmlElement xmlElement in xmlNodeList)
                        {
                            shippingCost = decimal.Parse(xmlElement.InnerText);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ad2.ExceptionHandler.Log(ex);
            }

            return shippingCost;
        }
        private static string GetAuthXML(string accessLicenseNumber, string userID, string password)
        {
            StringBuilder xmlAuthTemplate = new StringBuilder();

            xmlAuthTemplate.Append("<?xml version="1.0"?>");
            xmlAuthTemplate.Append("<AccessRequest xml:lang="en-US">");
            xmlAuthTemplate.Append(string.Format("   <AccessLicenseNumber>{0}</AccessLicenseNumber>", accessLicenseNumber));
            xmlAuthTemplate.Append(string.Format("   <UserId>{0}</UserId>", userID));
            xmlAuthTemplate.Append(string.Format("   <Password>{0}</Password>", password));
            xmlAuthTemplate.Append("</AccessRequest>");
            xmlAuthTemplate.Append("<?xml version="1.0"?>");

            return xmlAuthTemplate.ToString();
        }
        private static string GetRequestXML(string shipFromZipCode, string shipToZipCode, string serviceRateCode, string packageWeight)
        {
            StringBuilder xmlRequestTemplate = new StringBuilder();

            xmlRequestTemplate.Append("<RatingServiceSelectionRequest xml:lang="en-US">");
            xmlRequestTemplate.Append("  <Request>");
            xmlRequestTemplate.Append("    <TransactionReference>");
            xmlRequestTemplate.Append("      <CustomerContext>Rating and Service</CustomerContext>");
            xmlRequestTemplate.Append("      <XpciVersion>1.0001</XpciVersion>");
            xmlRequestTemplate.Append("    </TransactionReference>");
            xmlRequestTemplate.Append("    <RequestAction>Rate</RequestAction>");
            xmlRequestTemplate.Append("    <RequestOption>shop</RequestOption>");
            xmlRequestTemplate.Append("  </Request>");
            xmlRequestTemplate.Append("  <PickupType>");
            xmlRequestTemplate.Append("  <Code>01</Code>");
            xmlRequestTemplate.Append("  </PickupType>");
            xmlRequestTemplate.Append("  <Shipment>");
            xmlRequestTemplate.Append("    <Shipper>");
            xmlRequestTemplate.Append("      <Address>");
            xmlRequestTemplate.Append(string.Format("    <PostalCode>{0}</PostalCode>", shipFromZipCode));
            xmlRequestTemplate.Append("      </Address>");
            xmlRequestTemplate.Append("    </Shipper>");
            xmlRequestTemplate.Append("    <ShipTo>");
            xmlRequestTemplate.Append("      <Address>");
            xmlRequestTemplate.Append(string.Format("    <PostalCode>{0}</PostalCode>", shipToZipCode));
            xmlRequestTemplate.Append("      </Address>");
            xmlRequestTemplate.Append("    </ShipTo>");
            xmlRequestTemplate.Append("    <Service>");
            xmlRequestTemplate.Append(string.Format("    <Code>{0}</Code>", serviceRateCode));
            xmlRequestTemplate.Append("    </Service>");
            xmlRequestTemplate.Append("    <Package>");
            xmlRequestTemplate.Append("      <PackagingType>");
            xmlRequestTemplate.Append("        <Code>02</Code>");
            xmlRequestTemplate.Append("        <Description>Package</Description>");
            xmlRequestTemplate.Append("      </PackagingType>");
            xmlRequestTemplate.Append("      <Description>Rate Shopping</Description>");
            xmlRequestTemplate.Append("      <PackageWeight>");
            xmlRequestTemplate.Append(string.Format("        <Weight>{0}</Weight>", packageWeight));
            xmlRequestTemplate.Append("      </PackageWeight>");
            xmlRequestTemplate.Append("     </Package>");
            xmlRequestTemplate.Append("    <ShipmentServiceOptions/>");
            xmlRequestTemplate.Append("  </Shipment>");
            xmlRequestTemplate.Append("</RatingServiceSelectionRequest>");
            xmlRequestTemplate.Append("</RatingServiceSelectionRequest>");

            return xmlRequestTemplate.ToString();
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2009/02/calculate-shipping-cost-using-ups-webservice/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Send Templated Emails Using MailDefinition Object</title>
		<link>http://jesal.us/2008/10/send-templated-emails-using-maildefinition-object/</link>
		<comments>http://jesal.us/2008/10/send-templated-emails-using-maildefinition-object/#comments</comments>
		<pubDate>Sat, 25 Oct 2008 23:58:32 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[email]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=100</guid>
		<description><![CDATA[Recently I discovered a better way to format my email messages in ASP.NET using the MailDefinition object. It lets you to use an email template and define tokens which you want to replace in it. This helps keep the presentation and business layers clean &#038; seperate and lets the designers go in and edit the [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I discovered a better way to format my email messages in ASP.NET using the MailDefinition object. It lets you to use an email template and define tokens which you want to replace in it. This helps keep the presentation and business layers clean &#038; seperate and lets the designers go in and edit the email templates without having to navigate the StringBuilder jungle.</p>
<p>Here&#8217;s how its done.</p>
<pre name="code" class="c-sharp:nogutter">
private void SendEmail(long customerID)
{
	Customer customer = CustomerData.GetCustomer(customerID);

	MailDefinition mailDefinition = new MailDefinition();
	mailDefinition.BodyFileName = "~/Email-Templates/Order-Confirmation.html";
	mailDefinition.From = "no-reply@my-site.com";

	//Create a key-value collection of all the tokens you want to replace in your template...
	ListDictionary ldReplacements = new ListDictionary();
	ldReplacements.Add("<%FirstName%>", customer.FirstName);
	ldReplacements.Add("<%LastName%>", customer.LastName);
	ldReplacements.Add("<%Address1%>", customer.Address1);
	ldReplacements.Add("<%Address2%>", customer.Address2);
	ldReplacements.Add("<%City%>", customer.City);
	ldReplacements.Add("<%State%>", customer.State);
	ldReplacements.Add("<%Zip%>", customer.Zip);

	string mailTo = string.Format("{0} {1} <{2}>", customer.FirstName, customer.LastName, customer.EmailAddress);
	MailMessage mailMessage = mailDefinition.CreateMailMessage(mailTo, ldReplacements, this);
	mailMessage.From = new MailAddress("no-reply@my-site.com", "My Site");
	mailMessage.IsBodyHtml = true;
	mailMessage.Subject = "Order Confirmation";

	SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"].ToString(), 25);
	smtpClient.Send(mailMessage);
}
</pre>
<p>Your email template could be of any extension (txt, html, etc) as long as its in a text format. I personally like to keep it in HTML format so that we can preview the email template in a browser. Basically it&#8217;ll looks something like this -</p>
<pre name="code" class="html:nogutter">
Hello <%FirstName%> <%LastName%>,

Thank you for creating an account with us. Here are your details:

<%Address1%>,
<%Address2%>
<%City%>, <%State%> <%Zip%>

Thank You,
My Site
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/10/send-templated-emails-using-maildefinition-object/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

