Added valid date validation in jQuery validator


Hi,
Recently I got lots of error on mobile page, where I cannot give a nice date picker.
I use jQuery validator for form validations, but its date validation is not validating valid date.

If you use the new Date() function with 32nd as date, then it takes next month’s date.

I came up with adding more validations in default date validation method.

(function($) {
	/*
	 * This is a date validation fix,
	 * Because earlier it was validating invalid dates like '12//2/12' or '04/31/2012'
	 */
	/*
	 * Edit 1: Added year range: 1012 is invalid year, SQL datetime range is 1/1/1753 TO 12/31/9999
	 */
	 $.validator.addMethod("date", function(value, element) {
		return this.optional(element) || (/^\d{2}([\/])\d{2}\1\d{4}$/.test(value) && !/Invalid|NaN/.test(new Date(value)) && parseInt(value.match(/^\d{2}/)) == (new Date(value).getMonth()+1) && parseInt(value.match(/\d{4}/)) > 1752);
	});
})(jQuery);

Save the above code in one js file e.g. jquery.validate.datefix.js and include it after you include jQuery validator js.

Managing ColdFusion code formatting


Hi all!

Since I use eclipse as ColdFusion editor, I have installed cfeclipse plug-in for ColdFusion.

I got two issues which makes me writing this blog post. One is slowing down editing of large file in cfeclipse and proper code formatting which improves readability.

Since cfelipse is now providing more features, eclipse is now taking more time and gives a slow response in typing. My project has some files with more that 1200 lines to 10k lines! So eclipse becomes time-consuming if we try to edit those files.

cfmodule and cfinclude are two options that can be used to reduce the file size by splitting main file by your functionality. But if you are still stick and you don’t want to use them, then you can use notepad++ for those files.

Most of the ColdFusion guys aware of Notepad++’s plugin for ColdFusion. It is simply great! But Notepadd++ and its plug-ins are not yet compared with eclipse with efclipse.

I reviewed my files and those files are also having leading spaces in code indentation. I think tab is the best way to have white spaces for code indentation, because if you can move cursor with your keyboard’s arrow keys faster than if we have spaces. It can also reduce number of characters of your file.

Recently cfeclipse’s update provides color formatting for variable scopes and color formatting within cfscript tag.
They are now also providing css, JavaScript and SQL code formatting as well as. But the main issue is we do not need newline for each ColdFusion tag. For example:

<input type="checkbox" name="mycheckbox" <cfif form.mycheckbox EQ 1>checked</cfif>/>

So auto code formatting with Ctrl+Shift+F will not give you nice and intelligent output.

So I decided to remove leading spaces with tab characters, without using auto code formatter.

To see the tab and space characters, just enable the “Show symbols” option.

notepad-optionWhat my logic is to find all leading spaces and replace 4 spaces with one tab character.

space-issueRun this code with providing your large file which has mix of spaces and tab in code indentation and see the output!

<cfif FileExists("#ExpandPath('/codeformatter_out.cfm')#")>
	<cffile action="delete" file="#ExpandPath('/codeformatter_out.cfm')#"/>
</cfif>
<cfloop file= "#ExpandPath('/codeformatter_source.cfm')#" index="theLine">
	<cfset ret = ReFind("^[ \t]+",theLine, 1, true) > <!--- RegEx to file leading spaces (tab+spaces) --->
	<cfif ret.len[1] GT 0>
		<!--- Find space count --->
		<cfset totalspace = len(rereplace(left(theLine,ret.len[1]),'[^ ]+',"","all"))>
		<!--- Find tab count --->
		<cfset totaltab = len(rereplace(left(theLine,ret.len[1]),'[^\t]+',"","all"))>
		<!--- 4 space should be converted to 1 tab --->
		<cfset totalnewtab = ceiling(totalspace / 4)>
		<!--- Calculate total tab to set --->
		<cfset finaltab = totaltab + totalnewtab>
		<!--- Create tab string to replace --->
		<cfset tabStr = "">
		<cfloop from="1" to="#finaltab#" index="i">
			<cfset tabStr = tabStr & "	">
		</cfloop>
		<!--- Replace leading spaces with our tab string --->
		<cfset theLine = ReReplace(theLine,"^[ \t]+",tabStr)>
		<!--- Remove trailing spaces --->
		<cfset theLine = ReReplace(theLine,"[ \t]+$",'')>
	</cfif>
     <cffile action="append" file="#ExpandPath('/codeformatter_out.cfm')#" output="#theLine#"/>
</cfloop>

Search opening square bracket in SQL query with LIKE operator


Hi,

In my previous post, I’ve identified an issue of file name with square bracket in Amazon S3 URL wasn’t opening in FireFox.

So my next job was to rename the files, and update the path in database.

I wanted to search how many path has ‘[' or ']‘ bracket in file name (consider attachment as SQL table column name for convenient).

I wrote like:

WHERE attachment LIKE '%[%'

But this will not work. When I see MSDN link I came to know that % and [ are used as wild card characters, and I mixed them!!

Then I thought escaping it might work

WHERE attachment LIKE '%\[%'

Silly huh! finally I came up with following:

WHERE attachment LIKE '%[\[]%'

SignatureDoesNotMatch – Amazon S3 file opening issue in FireFox


Hi,

Yesterday I see a case that my file on Amazon S3 wasn’t opening in FireFox but it was opening in Chrome and Internet Explorer 9.

The issue was character encoding. My filename was containing square bracket ‘[' and ']‘.

‘[' converted to %5B and ']‘ converted to %5D

So I learned a lesson to replace special characters.

Problems, tips and tricks about Magento


Hello friends,

I am new to Magento. I find many configurations that has to be done before you make your Magento site live. So I though I should list out all important configurations at one place so that this list can also be used as checklist as well as tips and tricks for new Magento developers.

  • Install Magento on XAMPP
    Magento requires itself to be installed on a host name with at least one period ‘.’ in it, therefore installing to http://localhost doesn’t work. So, before you install it on your local machine, you should update your host file and add some domain name. For e.g. magento.local. In windows normally host file is located at C:/Windows/System32/drivers/etc/hosts location. In Linux it may be in /etc/hosts. Please refer this wiki page for more about Magento on XAMPP and WAMP. The only important section is note in that wiki page.
  • Linux/Ubuntu installation error: curl not enabled
    Please install php5-curl module. e.g. For Ubuntu “sudo apt-get install php5-curl”
  • Linux/Ubuntu installation warning: “Your web server is configured incorrectly. As a result, configuration files with sensitive information are accessible from the outside. Please contact your hosting provider.”
    To solve this issue, modify Apache site configuration from “AllowOverride None” to “AllowOverride All”
  • Installation warning: The URL “http://yourdomainname.com.local&#8221; is invalid.Response from server isn’t valid
    Domain name probably not pointing to your installation directory, try to update server host file and add your domain name to point to localhost IP.
  • Select correct time zone while you install Magento
    Please refer to this forum.
  • Use a better way to customize your site
    There are some good tips from community to turn off some Magento blocks here. Please go through that. I’d also like to refer this blog post. This will help you a lot.
  • Changing default logo and other important settings
    There is another nice wiki page here, that will some good points while you customize your Magento site.
  • Fix about Magento Admin notification issue
    It has been solved in Latest Magento version 1.7, but if you have previous versions you’ll notice an issue described in this forum.
  • Setting up cron
    To set up cron please refer this Magento wiki page. Ideally you should set cron to run every 5 minutes.
  • Make sure SEO is enabled
    To check it, go to System -> Configuration -> General -> web -> Search Engine Optimization
  • Make cron settings for currency conversion rate
    I was having a case where currency was listed in Magento but I was not able to get the conversion rate. Please refer this wiki page.
  • Setting up log cleaning
    By default log cleaning is not enabled, so you must need to configure it, other wise your database will grow surprisingly.
    To configure it, go to System -> Configuration -> Advanced -> System -> Open Log cleaning section. Please note that, this will be triggered by Magento cron job, so you must have to configure cron job for Magento. Please read more about log cleaning in this blog post.
  • Upgrading Magento to higher version
    Go to System -> Magento connect -> Magento connect manager. login with admin credentials. Then, go to section with name “Manage Existing Extensions” and click the button that says “Check for Upgrades”. To upgrade all Magento core extensions, just select “Mage_All_Latest” and select the upgrade action (only available if new version is available) and then click on commit changes button. Similarly your can also upgrade any other extension that you installed on your website.
  • Add CMS page links to top navigation
    Please refer to my previous post.
  • Moving Magento from One server to another
    This wiki page covers two methods to migrate Magento site from one server to another. From my point of view second method is more appropriate. Here are the steps that you can perform.

    1. Take back up of database and website files.
    2. Export data from old MySQL server
    3. Create new database on new server and import data that we’ve downloaded from old server.
    4. Table core_config_data has rows that need to be changed and updated with the new url.
      path:                       value:
      web/unsecure/base_url       http://[you_domain_here]/
      web/secure/base_url         https://[your_secure_domain_here]/
    5. Download all files from old server and upload it to new server
    6. Delete /var/cache and /var/session directory
    7. Modify /app/etc/local.xml file to update new database information
    8. Make sure that /var and /media should have read/write permission with recursive
    9. All is done! Now browse the new server
  • Add currency dropdown on top of the page
    Modify your local.xml file and add following code between the default tag:

     <reference name="header">
    <block type="directory/currency" name="store_currency_selector" as="store_currency_selector" before="top.menu" template="directory/currency.phtml"/>
    </reference>
    
  • Change three column layout to two column layout and update grid column count
    Modify your local.xml file and it should contains tags shown as bellow:
  •  <?xml version="1.0"?>
    <layout version="0.1.0">
    <default>
    <reference name="root">
    <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
    </reference>
    </default>
    <catalog_category_default>
    <reference name="product_list">
    <action method="setColumnCount">
    <count>4</count>
    </action>
    </reference>
    </catalog_category_default>
    <catalog_category_layered>
    <reference name="product_list">
    <action method="setColumnCount">
    <count>4</count>
    </action>
    </reference>
    </catalog_category_layered>
    <catalogsearch_result_index>
    <reference name="root">
    <action method="setTemplate"><template>page/2columns-left.phtml</template></action>
    </reference>
    <reference name="search_result_list">
    <action method="setColumnCount">
    <count>4</count>
    </action>
    </reference>
    </catalogsearch_result_index>
    </layout>
    
  • Add Facebook, twitter, Google plus buttons
    AddThis simplifies social sharing. You can get the Magento extension for AddThis from here.
  • Remove Email to friend link
    Go to System -> Configuration -> Catalog -> Email to a Friend -> Email templates -> Change Enabled to No
  • Add Banner slider
    Banner slider is a well known tool that you can use. To solve the issue of adding new slider image, please refer to this forum post.
  • User your SMTP server to send emails
    This extension will help you if your localhost is not allowed to send emails and even if you want different SMTP server.
  • 404 Page not found error when using newly installed extension
    logoff and login will solve that issue.
  • Email sending issue
    If you get an error like “Warning: Illegal offset type  in /lib/Zend/Mail.php on line 574″, Please refer to this and this post.
  • Solve issue of Service Temporarily Unavailable Magento
    Refer to this page.
magento_logo

Adding CMS page links to top navigation in Magento


Hello friends,

I had a site running on magento 1.6.2 CE.

To add a menu item, first of all you need to find out where it is added into template file.

Following file is rendering categories as a menu on top navigation

app/design/frontend/base/template/catalog/navigation/top.phtml

Basically you need to modify this file and add links in list.

To make the changes upgrade proof, you should copy this file and paste it in your template directory

e.g. app/design/frontend/default/YourThemeName/template/catalog/navigation/top.phtml

Now you add a link as follow:

<!--?php $_menu = $this--->renderCategoriesMenuHtml(0,'level-top') ?>
<!--?php if($_menu): ?--></pre>
<div class="nav-container">
<ul id="nav">
	<li><a href="/">Home</a></li>
	<li><!--?php echo $_menu ?--></li>
</ul>
</div>
<pre>
<!--?php endif ?-->

But this way you will need to modify file each and every time when you want to modify links. So it is better to load a static CMS block. To do so, render two CMS block as shown bellow:

<!--?php if($_menu): ?--></pre>
<div class="nav-container">

</div>
<pre>
<!--?php endif ?-->

Now create those two CMS blocks in CMS -> Static Block -> Add New Block

Block identifier: navbar_links1

</pre>
<ul>
	<li><a href="{{store url=">Home</a></li>
	<li><a href="{{store url=">Introduction</a></li>
</ul>
<pre>

Similarly create another block for navbar_links2. Please Note that, when you edit them, HTML editor automatically adds

    tag surrounding it. You should remove it when ever you edit blocks.

Above trick was working perfectly until I upgrade my site to Magento Community addition 1.7.

I take a look around page.xml layout, and I noticed that, now magento is rendering menu from the following template file:

app/design/frontend/base/template/page/html/topmenu.phtml

So in order to work our trick, you need to modify above file by the way did it before.

First copy that file to following location:

app/design/frontend/default/YourTemplateName/template/page/html/topmenu.phtml

Make the same changes as we did it in top.phtml (show in listing no 2). Delete our old modified file app/design/frontend/default/YourThemeName/template/catalog/navigation/top.phtml as we don’t need it now. Flush the cache and you are done!

Your menu links will be back!

Classic ASP SQL injection prevention by using query parameter


Hello friends,

Recently I got a client email that his site is affected by malware and Trojan virus. Google safe browsing tool and other firewall security gateway was blocking some of the site URLs.

Site was written in classic asp long ago by other company. When I look into the file contents, no files were modified. Normally if hackers get the ftp details then they modify files and add some iframe code that will load other virus affected sites. But this wasn’t case here. So there may be a case of SQL injection. When I looked into database tables, I found some of the fields with having some html code. That html code was loading other sites which are virus infected. Our site is not allowing anyone to add/edit records, however records were modified. This was done by SQL injection using query string parameter.

I looked into some of the pages, and I found page that lists records and records were filtered by some condition and by query string parameter.

In classic asp, most of the developers write an SQL query like following:

sql = " SELECT * FROM table WHERE id = " & Request("id") 

Executing such query easily opens a way for SQL injection. We must need to validate the variables used in SQL query.

Fortunately, we can do it by adding parameters in SQL query. Basically we need to create ADODB command object. A detailed example is show bellow:

<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Your connection string"

set cmd = server.createobject("ADODB.Command")
sql = " SELECT * FROM table WHERE id = ? or name like ?"

cmd.ActiveConnection = conn
cmd.CommandText = qText
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900
cmd.Parameters.Append cmd.CreateParameter("@id", adInteger, adParamInput, ,request("id"))
cmd.Parameters.Append cmd.CreateParameter("@name", adVarchar, adParamInput, 50, "%" & request("name") & "%")

set rs = cmd.Execute

Set rs = Nothing

Set conn = Nothing
%>

Also note that, when you add or append a parameter, name is not much important. Parameter position is the important thing. First ? mark will be replaced by first parameter and second ? mark with second parameter.

Please note that here we have used some VB constants. You need to declare them somewhere. You can include this asp file on the top of your page.