Wednesday, April 28, 2010

Adding Google Custom Search to your Blog

Adding Custom Search to your Blogspot Blog enhances its value and allows visitors to sift through your posts with ease. Adding Google Custom Search is not simple or for the fain at heart. It requires tons of patience, a keen eye and a good comfort level at playing with code. For a live demo, I have added the same to my blog as well, so feel free to try it out! Adding Google Custom Search is not simple, here are the steps that are required:
  1. Create a static page on Blogger for displaying Search Results
  2. Sign Up for Google AdSense - if you want to earn money
  3. Sign Up for Google Custom Search
  4. Update the static page with Google Custom Search Code
  5. Remove side bar & meta-data displayed on the static page
  6. Add search box on side bar
So here goes, get ready to get down & dirty with the details ...

1. Create a static page on Blogger

Create a static page on Blogger for displaying Search Results. Go to Posting > Edit Pages and click on the New Page button to create a new static page. Set the title as Search Results or anything appropriate and for now, enter placeholder text Search Results in the page. View this page and note down the URL of this page - this will be used in the later steps when configuring Google Custom Search.

2. Sign Up for Google AdSense

If you want to earn some money through the searches that are done on your site, you will need to sign-up for an adsense account. Here I am assuming that you already have one - if not, then just go ahead and sign up for one.

3. Sign Up for Google Custom Search

From inside the AdSense account, click on the link AdSense for Search and then follow the steps below:

  • Click on Single Page link at the top to view all the options in one page
  • Search Type: Select Only sites I select
  • Selected sites: If you have more than one site, enter one site per line for each of the websites you want to include in the search.
  • Optional Keywords: Enter keywords separated by space if you want to give hints to the search engine.
  • Opening of search results page: Select Open results within my own site and in the box below for Enter URL where search results will be displayed, enter the URL of the static page created in Step 1 above.
  • Ad Location: You can choose whichever option you like, but I personally prefer to go for Top and Bottom
  • Name Your Search Engine: give a name for your custom search engine
  • Fill in all the other remaining fields as per your requirement
  • Press the Submit and Get Code button to get the Javascript code that you need to put into the static page

4. Update static page on Blogger

Go to Posting > Edit Pages and click on the Edit link for the static page created above. Then:

  1. Copy code from Search box code and paste it here
  2. Enter a break tag <br>
  3. Copy code from Search results code and paste it here

5. Remove side bar & meta-data displayed on the static page

Now this is the tricky part which requires you to change the template. You can skip this step if you are OK with having the widgets display on the right column. Note: take a backup of your template before proceeding!
Go to Layout > Edit HTML and check the box Expand Widget Templates. Then add the line: to the following 3 places:
To remove the Post Metadata (Author, Tags, Time) from Static page
Lines 1 and 19 in this code snippet

       <b:if cond="data:blog.pageType != "static_page"">
   <div class="postmeta">
   <b:if cond="data:top.showAuthor">
      Posted by
      <span class="fn"><data:post.author/></span>
      </b:if> |
   <b:if cond="data:post.labels">
   Posted in
        <b:loop values="data:post.labels" var="label">
          <a expr:href="data:label.url" rel="tag"><data:label.name/></a><b:if cond="data:label.isLast != "true"">,</b:if>
        </b:loop>
      </b:if> |
   <b:if cond="data:top.showTimestamp">
      <b:if cond="data:post.url">
      Posted on <data:post.timestamp/> 
      </b:if>
      </b:if>
   </div>
      </b:if>
 </div>

To remove the "Continue Reading" or similar link from Static page
Lines 2 and 7 in this code snippet
 <b:if cond="data:blog.pageType != "item"">
        <b:if cond="data:blog.pageType != "static_page""><br/>
 <div class="postmetadata">
    <p><a expr:href="data:post.url">Continue Reading</a></p>
 </div>
    </b:if>
    </b:if>

To remove the right Column widgets from Static page
Lines 2 and 14 in this code snippet
 <!-- Body_right -->
<b:if cond="data:blog.pageType != "static_page"">
    <div id="body_right">
   <!-- Sidebar Ads -->
...
...
   <!-- /Sidebar Ads -->
   
   <!-- Sidebar -->
   <div id="sidebars">
...
...
      </div>
</b:if>
   <!-- /Body_right -->

6. Add search box on side bar

To add search box on side bar, go to Layout > Page Elements and click on the Add a Gadget link on the bottom right. Add a HTML/JavaScript widget and in the window that opens up, enter the following:

  • Title: Search or something similar
  • Content: Here paste the code from Google Custom Search / AdSense for Content from the box Search box code
And after these long & complicated steps, you should have your Google Custom Search with AdSense on your Blogger Blog ready!!!

Thursday, April 15, 2010

Implement reCAPTCHA with Classic ASP and Validate with AJAX

A friend asked me to help implementing reCAPTCHA with classic ASP which I successfully managed to implement even though I have not dabbled much with ASP - read the implementation here.
So now the expectations rise and he asks me to validate reCaptcha using AJAX - I do not have any experience of AJAX combined with ASP either.

Going through the resources section of the recaptcha.net site did not help much in this regard. So here are the steps that I did to achieve this. Note that most parts of the solution here have been taken from various pages on the net which are listed at the bottom of this post in the References section.


There are 6 parts of the code as follows:
  1. JavaScript to create reCaptcha on the page that has the input form
  2. Insert the created reCaptcha in the desired location
  3. Generic JavaScript to make AJAX call
  4. Make AJAX call to Server-side component to validate reCaptcha
  5. Handle AJAX validation response from server-side component
  6. Server side component to validate the reCaptcha

1. JavaScript to create reCaptcha on the page that has the input form
Here is the code that needs to be placed in the ASP file to generate the JavaScript which when called, generates the code for reCaptcha. The generated string needs to be placed in your form where you want the reCaptcha to be displayed.

<%
recaptcha_public_key = "XXXXXXXXXXXXXXXX"
function recaptcha_challenge_writer(publickey) 
  recaptcha_challenge_writer = "<script type=""text/javascript"">" & _ 
 "var RecaptchaOptions = {" & _ 
 " theme : 'red'," & _ 
 " tabindex : 0" & _ 
 "};" & _ 
 "</script>" & _ 
 "<script type=""text/javascript"" src=""http://api.recaptcha.net/challenge?k=" & publickey & """></script>" & _ 
 "<noscript>" & _ 
 "<iframe src=""http://api.recaptcha.net/noscript?k=" & publickey & """ frameborder=""1""></iframe>
 " & _ 
 "<textarea name=""recaptcha_challenge_field"" id=""recaptcha_challenge_field"" rows=""3"" cols=""40""></textarea>" & _ 
 "<input type=""hidden"" name=""recaptcha_response_field"" id=""recaptcha_response_field"" value=""manual_challenge"">" & _ 
 "</noscript>" 
end function 
%>

2. Insert the created reCaptcha in the desired location
Here is how you need to place the code in your form where you want the reCaptcha to be displayed.

<%=recaptcha_challenge_writer(recaptcha_public_key)%>

3. Generic JavaScript to make AJAX call
Here is a generic JavaScript function to make an AJAX call


4. Make AJAX call to Server-side component to validate reCaptcha
Here is the JavaScript "onClick" function that will make the specific call to the server-side component to validate the reCaptcha input.



5. Handle AJAX validation response from server-side component
Here code that needs to be put in the asp file that processes the submitted form.

// The function for handling the response from the server
var showMessageResponse = function (oXML) { 
    
    // get the response text, into a variable
 var response = oXML.responseText;
    
    // act on the result from the server
 if (response == "PASS") {
  //alert("Captcha Passed ...");
  document.getElementById("Form1").action = "process_form.asp";
  document.getElementById("Form1").submit();
 }  else {
        // Reload the captcha image if the validation failed & alert the user
 alert("Captcha Failed. Please try again ...");
 Recaptcha.reload();
 }
};

6. Server side component to validate the reCaptcha
Here code that needs to be put in the asp file that processes the submitted form.

'Define some variables to be used on page
dim pubkey, privkey, challenge, form_response, test_captcha, recaptcha_confirm

'Customize your public and private keys and other variables
pubkey = "XXXXXXXXXXXXXXXX"
privkey = "XXXXXXXXXXXXXXXX"

' Get the user input
challenge = Request.Form("recaptcha_challenge_field")
form_response = Request.Form("recaptcha_response_field")

' Generate the POST string for reCaptcha
Dim VarString
VarString = _
"privatekey=" & privkey & _
"&remoteip=" & Request.ServerVariables("REMOTE_ADDR") & _
"&challenge=" & challenge & _
"&response=" & form_response

' Make an AJAX call to validate input reCaptcha
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
if isNull(objXmlHttp) then
Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
end if
objXmlHttp.open "POST", "http://api-verify.recaptcha.net/verify", False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send VarString

' Receive response from reCaptcha server
Dim ResponseString
ResponseString = split(objXmlHttp.responseText, vblf)
Set objXmlHttp = Nothing

if ResponseString(0) = "true" then
'They answered captcha correctly
    response.write("PASS")
else
'They answered captcha incorrectly
    response.write("FAIL")
end if


Note:
  1. Of course, you need to sign-up for a free reCaptcha account at reCaptcha.net.
  2. The above steps 1, 3, 4 & 5 can be put in the same script block.
  3. The above step 2 needs to be put in the place in the form where reCaptcha is to be shown.
  4. Remember to substitute the public & private keys with the ones that you get when you sign up for a free reCaptcha account.
  5. This is a very basic, no-frills version. You can modularize, clean-up, optimize and add more error-handling. But this should be good enough to get you started!

References:
  1. This Google Groups post
  2. reCaptcha resources page
  3. This post on Jeff Niblack's Blog
  4. This post on World of Code Blog
  5. This blog post on Dark Side of Carton.

Syntax Highlighter now available for Blogger

I had been putting off using Syntax Highlighter for quite some time as it required me to host the files somewhere and then use them. Also, using it for a Blogger Blog did not seem to be so straight-forward and did not produce clean results. This was the status when I had last checked it out quite some time back.

So when reviewed a post I wrote with a lot of code in it, I was saddened that I had not add Syntax Highlighter to my blog. So I decided to take a second look and was pleasantly surprised to see both my issues resolved! Now there was an option for using the hosted version of the files and also there was a very neat blogger mode!

So now finally, you don't need to look around for someone to host the Syntax Highlighter files for you - you can use the hosted version of the Syntax Highlighter files. And there is a very good bloggerMode! which helps to integrates very cleanly with Blogger.

Implementing reCaptcha in Classic ASP

A friend of mine was very impressed with reCaptcha and wanted me to help him implement on his website that uses classic ASP! Going through the posts mentioned in the reference below gave me a bit of an idea but the solution was not very clear. Here's how I finally implemented it...

There are 3 parts of the code as follows:
  1. JavaScript to create reCaptcha on the page that has the input form
  2. Insert the created reCaptcha in the desired location
  3. Server side component to validate the reCaptcha

1. JavaScript to create reCaptcha on the page that has the input form
Here is the code that needs to be placed in the ASP file to generate the JavaScript which when called, generates the code for reCaptcha. The generated string needs to be placed in your form where you want the reCaptcha to be displayed.

<%
recaptcha_public_key = "XXXXXXXXXXXXXXXX"
function recaptcha_challenge_writer(publickey) 
  recaptcha_challenge_writer = "<script type=""text/javascript"">" & _ 
 "var RecaptchaOptions = {" & _ 
 " theme : 'red'," & _ 
 " tabindex : 0" & _ 
 "};" & _ 
 "</script>" & _ 
 "<script type=""text/javascript"" src=""http://api.recaptcha.net/challenge?k=" & publickey & """></script>" & _ 
 "<noscript>" & _ 
 "<iframe src=""http://api.recaptcha.net/noscript?k=" & publickey & """ frameborder=""1""></iframe>
 " & _ 
 "<textarea name=""recaptcha_challenge_field"" id=""recaptcha_challenge_field"" rows=""3"" cols=""40""></textarea>" & _ 
 "<input type=""hidden"" name=""recaptcha_response_field"" id=""recaptcha_response_field"" value=""manual_challenge"">" & _ 
 "</noscript>" 
end function 
%>

2. Insert the created reCaptcha in the desired location
Here is how you need to place the code in your form where you want the reCaptcha to be displayed.

<%=recaptcha_challenge_writer(recaptcha_public_key)%>

3. Server side component to validate the reCaptcha
Here code that needs to be put in the asp file that processes the submitted form.

'Define some variables to be used on page
dim pubkey, privkey, challenge, form_response, test_captcha, recaptcha_confirm

'Customize your public and private keys and other variables
pubkey = "XXXXXXXXXXXXXXXX"
privkey = "XXXXXXXXXXXXXXXX"

' Get the user input
challenge = Request.Form("recaptcha_challenge_field")
form_response = Request.Form("recaptcha_response_field")

' Generate the POST string for reCaptcha
Dim VarString
VarString = _
"privatekey=" & privkey & _
"&remoteip=" & Request.ServerVariables("REMOTE_ADDR") & _
"&challenge=" & challenge & _
"&response=" & form_response

' Make an AJAX call to validate input reCaptcha
Dim objXmlHttp
Set objXmlHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
if isNull(objXmlHttp) then
Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
end if
objXmlHttp.open "POST", "http://api-verify.recaptcha.net/verify", False
objXmlHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXmlHttp.send VarString

' Receive response from reCaptcha server
Dim ResponseString
ResponseString = split(objXmlHttp.responseText, vblf)
Set objXmlHttp = Nothing

if ResponseString(0) = "true" then
'They answered captcha correctly
''' Handle Success scenario
else
'They answered captcha incorrectly
''' Handle Failure scenario
end if


Note:
  1. Of course, you need to sign-up for a free reCaptcha account at reCaptcha.net.
  2. The code in step 3 above needs to be put in the top of the file which processes your submitted form - the asp file that is mentioned in the action of this particular form. The above code needs to be executed before anything else in that file.
  3. It's regular processing steps should be put in the if block (line 37) that has the comment that the user answered the captcha correctly.
  4. Error message display logic should go into the else block (line 40) that has the comment that the user answered the captcha incorrectly.
  5. Remember to substitute the public & private keys with the ones that you get when you sign up for a free reCaptcha account.
  6. This is a very basic, no-frills version. You can modularize, clean-up, optimize and add more error-handling. But this should be good enough to get you started!

References:
  1. This Google Groups post
  2. reCaptcha resources page
  3. This post on Jeff Niblack's Blog
  4. This post on World of Code Blog

Are campaigns like "Big Picture" really effective?

I sure got my travel mug today and got free coffee from Starbucks. Starbucks is offering free coffee today (April 15th) to encourage people to reduce usage of paper cups - read my post about that here. This opens up the debate that whether these kind of programs really work? Here's my take ...

First hand experience - lugging around the travel mug is a pain which I am not ready to do everyday. The coffee was good, but cleaning the travel mug that has a narrow bottom was real pain as well. And God save you in case you got caught up in work / meeting and the leftover coffee in the travel mug dries up - cleaning it will require way more effort than you can imagine. These are the non-material negatives to using the travel mug.

Now coming to the material aspect - buying a travel mug costs some dough and if you go in for a "cool" one, get ready to be set back by at least 10 bucks. But that's only one time for however long you can manage to hold onto the mug. However, washing the travel mug with (running) hot water and soap after every use will require investing in soap & scrubber, add to the bill for heating water and use up your time {Remember - Time = Money!}. Also, producing the energy to heat the water may not be exactly soft on the planet either - but we may not know or notice that exactly.

Now for the psychological aspect of this issue. Most people will take this campaign as an opportunity to get *FREE* coffee. Many people may even drive extra miles just for this and in the process end up spending the cost of the coffee on gas instead! And from the very next day - most people will revert to their normal routine and use (and throw away) paper cups, tissues, plastic cutlery left and right as usual. Very very very few people would actually have a change of heart and
change their habits in a single attempt of such a one day campaign.

Even if I had not got the chance to get the free coffee, I would have sub-consciously noted that this is a good company which I should patronize the next time I am going to buy a product that they offer. This gives the company huge advantage over the competition. So in the end, what is gained is that people got free coffee and the company scores brownie points for being & encouraging people to go green as well as get a lot of cheap, effective & useful advertisement.

So, what do you think? And what would you do?!

Wednesday, April 14, 2010

Starbucks to Make a Difference with the Big Picture

Starbucks is trying to make a difference through its The Big Picture Green Project. Starbucks is asking general public to join the movement and on April 15th, it is encouraging people to reduce their usage of paper cups by giving free brewed coffee to those who bring in a reusable travel mug into their local Starbucks store. Their quote: One person can save trees, together we can save forests. is really worth working towards!

It is good to such big corporations like Starbucks sharing their responsibilities towards our communities and the planet and trying to make a difference. I wish more corporations follow the lead and do such campaigns to make this planet a better place to live in!

Thursday, April 8, 2010

URL Rewrite very slow on IIS7

My friend has an ASP shopping cart running on Windows 2008 Server + IIS7 + SQL Server. This cart does not support SEO / user friendly URLs and apparently due to that, his site was getting very low rankings on the search engines. He called me in to help him out implement URL Rewriting to resolve this. Here is my experience with this problem and finally how I went about resolving this.

So the first step was to install the URL Rewrite Module 2.0 for IIS. Next was to configure the rewriting of the URLs - the cart produced URLs of the form store/listItems.asp?cat=123&item=456. The item id number and the corresponding category id number changed for different items so putting in a generic regular expression would not work. So we would need to create static rewrite maps to achieve our goal.

So I created a rewrite map with entries like /store/listItems.asp?cat=123&item=456 mapped to /Item1 and /store/listItems.asp?cat=123&item=457 mapped to /Item2 and so on. This worked but the page did not come up properly. Investigation revealed that this was due to the HTML having relative URLs for CSS, Image & JavaScript files. I changed paths to absolute paths and lo-behold it was working fine! However, when using the user-friendly URL, the pages would come up quite slow compared to the page display using the old URLs.

In fact the pages came up so slow that we had to scrap this idea and look for other alternatives. Finally, after a lot of investigation, we fixed on the ages-old method of creating static HTML index files in folders named by each category. The header, footer & navigation menus would be common and kept in common folder. I know that this is not such a good idea and will result in creation of hundreds of folders with only an index file. But what the heck - it is simple, it works and it gets the job done!

Friday, April 2, 2010

Cheap Webhosting Deals

It seems that April is the month for Cheap Web Hosting Deals!!!
Here is a round-up of the cheapest (but not necessarily the best) web hosting deals I found out.

However, my personal favorite is always BlueHost for their excellent support & fast servers. Check out my post on the same here.

NOTE: No guarantees on the validity of the offers or the quality of the services. I am in no way connected to any of these hosting companies and the links provided are direct links (no affiliate tracking code). I do not gain in any way from you clicking on any of these links and/or signing up for any of these offers!!!


Lifetime Webhosting for $79
HostSure is offering a full featured lifetime web hosting for only $79 where most companies offer that for $60-$100/year.

Facade Host
Facade Host is offering shared web hosting packages for as low as only only $0.85/month where most companies offer that for $2-$5/month. Use coupon code april for a further 20% discount!

Cookie Host
Cookie Host is offering shared web hosting packages for as low as only only $5/year where most companies offer that for $60-$100/year. Note that the promotion starts on April 7th 2010 and is valid only for new hosting accounts. The good thing is that they do not automatically rebill you at the end of the first year and you will be given the option to renew at the then prevailing regular price.

Just Host
Just Host is offering a full featured unlimited web hosting with free domain for the life of hosting for only $3.45/month when prepaying for 2 years. Use coupon code 50OFF for a further discount to bring down the price to $2.95/month when prepaying for 2 years!

Fat Cow
Fat Cow is offering a full featured unlimited "green" web hosting with free domain for the life of hosting for only $66/year!

Dream Host
Dream Host is offering a full featured unlimited "green" web hosting with free domain for the life of hosting for only $9.24/year with coupon code 777!

Daily Razor
Daily Razor is offering a full featured unlimited web hosting for only $2.95/month. Use coupon code 15PD for another 15% discount!

NOTE: Not all of these plans may suit your needs

LinkWithin

Related Posts Plugin for WordPress, Blogger...