<?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</title>
	<atom:link href="http://jesal.us/feed/" rel="self" type="application/rss+xml" />
	<link>http://jesal.us</link>
	<description></description>
	<lastBuildDate>Fri, 19 Mar 2010 05:32:28 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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()
    {
        [...]]]></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>2</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>11</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 these [...]]]></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
{
    public static string Link(this [...]]]></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>&#8217;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>4</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>1</slash:comments>
		</item>
		<item>
		<title>Create PDF Forms using iTextSharp</title>
		<link>http://jesal.us/2008/10/create-pdf-forms-using-itextsharp/</link>
		<comments>http://jesal.us/2008/10/create-pdf-forms-using-itextsharp/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 17:31:10 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[itextsharp]]></category>
		<category><![CDATA[pdf]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=98</guid>
		<description><![CDATA[Generating PDF forms in .NET has always been somewhat messy and complicated. I&#8217;ve seen people convert raw HTML to PDF or adding and formatting form elements to a PDF doc in code behind, etc. All those methods are highly time consuming and tricky. Easiest way to create PDF Forms is by using iTextSharp (open source) [...]]]></description>
			<content:encoded><![CDATA[<p>Generating PDF forms in .NET has always been somewhat messy and complicated. I&#8217;ve seen people convert raw HTML to PDF or adding and formatting form elements to a PDF doc in code behind, etc. All those methods are highly time consuming and tricky. Easiest way to create PDF Forms is by using <a href="http://itextsharp.sourceforge.net/" target="_blank">iTextSharp</a> (open source) and <a href="http://www.adobe.com/products/livecycle/designer/" target="_blank">Adobe LiveCycle Designer</a>. </p>
<p>You can just create your custom form template using LiveCycle and then data bind the form fields using iTextSharp like this:</p>
<pre name="code" class="c-sharp:nogutter">
User user = UserData.GetUserByID(userID);
string randomFileName = Helpers.GetRandomFileName();
string formTemplate = Server.MapPath("~/FormTemplate.pdf");
string formOutput = Server.MapPath(string.Format("~/downloads/Forms/Form-{0}.pdf", randomFileName));

PdfReader reader = new PdfReader(formTemplate);
PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(formOutput, System.IO.FileMode.Create));
AcroFields fields = stamper.AcroFields;

// set form fields
fields.SetField("Date", DateTime.Now.ToShortDateString());
fields.SetField("FirstName", user.FirstName);
fields.SetField("LastName", user.LastName);
fields.SetField("Address1", user.Address1);
fields.SetField("Address2", user.Address2);
fields.SetField("City", user.City);
fields.SetField("State", user.State);
fields.SetField("Zip", user.Zip);
fields.SetField("Email", user.Email);
fields.SetField("Phone", user.Phone);

// set document info
System.Collections.Hashtable info = new System.Collections.Hashtable();
info["Title"] = "User Information Form";
info["Author"] = "My Client";
info["Creator"] = "My Company";
stamper.MoreInfo = info;

// flatten form fields and close document
stamper.FormFlattening = true;
stamper.Close();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/10/create-pdf-forms-using-itextsharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ADO.NET Data Access Template</title>
		<link>http://jesal.us/2008/10/adonet-data-access-template/</link>
		<comments>http://jesal.us/2008/10/adonet-data-access-template/#comments</comments>
		<pubDate>Sat, 04 Oct 2008 23:32:59 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ado.net]]></category>
		<category><![CDATA[bestpractice]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=97</guid>
		<description><![CDATA[Here&#8217;s a basic ADO.NET data access template with a SqlCacheDependency. Just wanted to post this for my future reference.

public static DataSet GetData(long itemID)
{
    DataSet ds = new DataSet();
    string cacheKey = Helpers.GetCacheKey(itemID); //Get a cache key unique to this method.

    if (HttpContext.Current.Cache[cacheKey] != null)
   [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a basic ADO.NET data access template with a <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.sqlcachedependency.aspx">SqlCacheDependency</a>. Just wanted to post this for my future reference.</p>
<pre name="code" class="c-sharp:nogutter">
public static DataSet GetData(long itemID)
{
    DataSet ds = new DataSet();
    string cacheKey = Helpers.GetCacheKey(itemID); //Get a cache key unique to this method.

    if (HttpContext.Current.Cache[cacheKey] != null)
    {
        ds = (DataSet)HttpContext.Current.Cache[cacheKey];
    }
    else
    {
        using (SqlConnection sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        {
            using (SqlCommand sqlCommand = new SqlCommand())
            {
                sqlCommand.Connection = sqlConnection;
                sqlCommand.CommandType = CommandType.StoredProcedure;
                sqlCommand.CommandText = "sp_Items_GetItemByID";
                sqlCommand.Parameters.Add("@itemID", SqlDbType.BigInt).Value = itemID;
                sqlConnection.Open();

                using (SqlDataAdapter da = new SqlDataAdapter(sqlCommand))
                {
                    da.Fill(ds);
                }
            }
        }

        SqlCacheDependency sqlCacheDependency = new System.Web.Caching.SqlCacheDependency(WebConfigurationManager.AppSettings["DatabaseName"], "Items");
        HttpContext.Current.Cache.Insert(cacheKey, ds, sqlCacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
    }

    return ds;
}
</pre>
<p>Note that I&#8217;ve employed most of the recommended best practices like caching, &#8220;using&#8221; keywords, stored procedures and connection string inside web.config. </p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/10/adonet-data-access-template/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Blocks Inside Master Pages</title>
		<link>http://jesal.us/2008/09/code-blocks-inside-master-pages/</link>
		<comments>http://jesal.us/2008/09/code-blocks-inside-master-pages/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 18:22:49 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[masterpages]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=96</guid>
		<description><![CDATA[Some time ago I kept getting this error in one of the projects I was working on:
The Controls collection cannot be modified because the control contains code blocks (i.e. ).
I spent quite some time trying to figure it out. Finally after hours of searching I found out that Code Blocks Inside Master Pages Cause Trouble.
I [...]]]></description>
			<content:encoded><![CDATA[<p>Some time ago I kept getting this error in one of the projects I was working on:</p>
<p><strong>The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).</strong></p>
<p>I spent quite some time trying to figure it out. Finally after hours of searching I found out that <a href="http://aspnetresources.com/blog/code_blocks_inside_master_pages_cause_trouble.aspx" target="_blank">Code Blocks Inside Master Pages Cause Trouble</a>.</p>
<p>I was using code blocks inside the head tag of all the MasterPages to resolve paths at runtime:</p>
<pre>
&lt;link rel="stylesheet" href="&lt;%= ResolveUrl("~/myStyleSheet.css") %&gt;" type="text/css" /&gt;
&lt;script type="text/javascript" src="&lt;%= ResolveUrl("~/myJavaScript.js") %&gt;"&gt;&lt;/script&gt;
</pre>
<p>Fortunately <a href="http://aspnetresources.com/blog/code_blocks_inside_master_pages_cause_trouble.aspx">Milan Negovan</a> proposed a quick workaround which saved a lot of time.</p>
<p>Basically, the workaround is to change the code blocks to data binding expressions (<%# ... %>). </p>
<pre>
&lt;link rel="stylesheet" href="&lt;%# ResolveUrl("~/myStyleSheet.css") %&gt;" type="text/css" /&gt;
&lt;script type="text/javascript" src="&lt;%# ResolveUrl("~/myJavaScript.js") %&gt;"&gt;&lt;/script&gt;
</pre>
<p>and adding this to the master page code behind:</p>
<pre name="code" class="csharp:nogutter">
protected override void OnLoad (EventArgs e)
{
  base.OnLoad (e);
  Page.Header.DataBind ();
}
</pre>
<p>Since HtmlHead ultimately derives from Control and everything that derives from Control has a DataBind() method, adding that one line above would force the header to resolve data binding expressions.</p>
<p>Thats it, that does the trick!</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/09/code-blocks-inside-master-pages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to setup an asp.net website on localhost</title>
		<link>http://jesal.us/2008/09/how-to-setup-an-aspnet-website-on-localhost/</link>
		<comments>http://jesal.us/2008/09/how-to-setup-an-aspnet-website-on-localhost/#comments</comments>
		<pubDate>Fri, 12 Sep 2008 22:35:32 +0000</pubDate>
		<dc:creator>J</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[iis]]></category>

		<guid isPermaLink="false">http://jesal.us/blog/?p=95</guid>
		<description><![CDATA[First lets start by setting up the site in IIS&#8230;
1.Open IIS  by double-clicking on Control Panel->Administrative Tools->Internet Information Services
2.Right Click on Web Sites->Default Web Site
3.Click on Properties->Home Directory and choose the location of your website

Now lets give the ASPNET account the appropriate permissions to access that directory&#8230; 
4. Using My Computer or the Windows [...]]]></description>
			<content:encoded><![CDATA[<p><strong>First lets start by setting up the site in IIS&#8230;</strong></p>
<p>1.Open IIS  by double-clicking on <strong>Control Panel->Administrative Tools->Internet Information Services</strong></p>
<p>2.Right Click on <strong>Web Sites->Default Web Site</strong></p>
<p>3.Click on <strong>Properties->Home Directory</strong> and choose the location of your website<br />
<img src="http://jesal.us/wp-content/uploads/sc1.jpg" /></p>
<p><strong>Now lets give the ASPNET account the appropriate permissions to access that directory&#8230;</strong> </p>
<p>4. Using My Computer or the Windows Explorer, navigate to the folder containing the website you choose in the previous step </p>
<p>5. Right click on the folder and and go to <strong>Properties->Security</strong></p>
<p>5. On the Security tab, click on <strong>Add</strong> to locate the ASPNET account<br />
<img src="http://jesal.us/wp-content/uploads/sc2.jpg" /></p>
<p>6. Click on <strong>Locations</strong> and select the local machine<br />
<img src="http://jesal.us/wp-content/uploads/sc3.jpg" /></p>
<p>7. Click on <strong>Advanced->Find Now</strong> to list all the user accounts on your local machine<br />
<img src="http://jesal.us/wp-content/uploads/sc4.jpg" /></p>
<p>8. Choose <strong>ASPNET</strong> and click on OK. (If you don&#8217;t see ASPNET account in there, go to step 11)</p>
<p>9. Return to the security tab. Select the ASPNET user account and check the <strong>Full Control</strong> checkbox under the allow column. Click OK.<br />
<img src="http://jesal.us/wp-content/uploads/sc5.jpg" /></p>
<p>10. Thats it! You should now be able to go to http://localhost/ in your browser window and see your website.</p>
<p><strong>If you don&#8217;t see an ASP.NET account in Step 8 then&#8230;</strong></p>
<p>11. Run &#8220;<strong>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ aspnet_regiis.exe -i -enable</strong>&#8221; in the command line window and then repeat steps 1 through 10.</p>
<p><strong>Following steps are optional. They help you configure your web project to automatically reference the local web-server when you run or debug a site instead of launching the built-in web-server itself&#8230;</strong></p>
<p>12. Open Visual Studio and select your web-project in the solution explorer, right click and select <strong>Property pages</strong>.</p>
<p>13. Select the <strong>Start Options</strong> from the left navigation, and under <strong>Server</strong> change the radio button value from &#8216;Use default Web server&#8217; to <strong>&#8216;Use custom server&#8217;</strong>. Then set the Base URL value to be: http://localhost/<br />
<img src="http://jesal.us/wp-content/uploads/sc6.jpg" /></p>
<p>Now, when you click on any page in the app and then hit F5 or Ctrl-F5, the IDE will use the local web-server instead of popping up its own.</p>
]]></content:encoded>
			<wfw:commentRss>http://jesal.us/2008/09/how-to-setup-an-aspnet-website-on-localhost/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
